How to write a (MySQL) "LIMIT" in SQL Server? - mysql

How do I convert a MySQL query with LIMIT to a SQL Server query?
SELECT *
FROM tableEating
WHERE person = '$identity'
LIMIT 1;

LIMIT does not work in T-SQL. Use TOP instead:
SELECT TOP(1) * FROM tableEating WHERE person = '$identity';
As Aaron says, you also need an ORDER BY if you don't want to get an arbitrary row.

LIMIT does not work and TOP(1) may also not work in nested statements.
So the right approach is to use OFFSET... FETCH NEXT:
SELECT * FROM TableName
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
That basically tells TSQL to take one row (NEXT 1 ROWS ONLY) starting from the first one (OFFSET 0).

Take a look at the Microsoft page for 2008, later versions work the same way. If you like to do it dynamic use:
DECLARE #xCount INT = 20
SELECT TOP(#xCount) * FROM ...

Related

Query in MySQL and SQL Server?

I have a problem to a help of every people:
In Mysql, my query:
select * from readquestion where readexerciseid= "+readexerciseid+" limit "+(start-1)+", "+count+";
I want to ask with this query in SQL Server, how should I do this?
In SQLServer use 'top' keyword to limit the results.
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact on performance.
Sytax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
Eg:
int count = start - 1 + count; //calculate limit here
"select top "+ count +" * from readquestion where readexerciseid= "+readexerciseid
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
In mysql use 'limit' keyword to limit the results.
syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
E.g.:
int count = start - 1 + count; //calculate limit here
"select * from readquestion where readexerciseid= "+readexerciseid+" limit "+ count

Return only one tuple of SQL query result

I want to do a query like
select * from chr2;
but only have MySQL return the first tuple (or an arbitrary) tuple instead of all of them.
How do I do it?
Use the LIMIT clause:
SELECT * FROM chr2 LIMIT 1;
If you want an arbitrary row returned, you have to sort your rows by an random col like this (MySQL docu):
SELECT * FROM chr2
ORDER BY RAND()
LIMIT 1;
On large tables, however, you might run into performance problems with this, as there a random value has to be created for each row and the table has to be sorted according to this column.
Try this ::
select * from chr2 limit 1

mysql query based on length of string in a column

I am trying to query a table in mysql based on the length of a string in a specific column. I know mysql has a function called LENGTH(), but that returns the length of the string. I want to be able to pull data based on the result of the LENGTH() function.
Example:
SELECT * table WHERE LENGTH(word) = 6
of course that does not work. I read through http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function%5Flength but could not find anything to help me.
yes I could make something in PhP to accomplish this, but I would like to do it at the query level.
Any help?
Try:
SELECT *
FROM table
WHERE LENGTH(RTRIM(word)) = 6
I believe you wanted to use query SELECT * FROM tableName WHERE LENGTH(word) = 6; (assuming that the word is name of column in tableName).
This is very unfortunate solution on large tables, you should create new column and use UPDATE tableName SET wordLength = LENGTH( word).

MySQL Wildcard for "=" - is there one

So,
SELECT * FROM table WHERE col LIKE '%'
will return everything. Is there a wildcard for the query
SELECT * FROM table WHERE col = '*'
Clearly * doesn't work, I just put it there to indicate where I'd like a wildcard. The column I'm selecting from contains an integer between 1 and 12, and I want to be able to select either all records with a particular number, or all records with a wildcard.
Thanks,
LIKE is basically the same as =, except LIKE lets you use wildcards.
These two queries will return the same results:
SELECT * FROM table WHERE col LIKE 'xyz';
SELECT * FROM table WHERE col='xyz';
Without a '%' in the LIKE query, it is effectively the same as '='.
If you're doing a selection on an integer column, you should consider using the IN() or BETWEEN operators. It sounds like you have two separate conditions that should be handled in your code however, rather than in the query, as your conditions dictate that you need at least two different kinds of queries.
Edit: I should clarify that LIKE and = are similar only in normal, humdrum string comparison usage. You should check the MySQL Manual for specifics on how it works, as there are situations where it's not the same (such as language sets).
If you want to select everything, why are you attaching the WHERE clause at all? Just leave it off conditionally instead of putting a wildcard into it.
The reason for using LIKE is because the = does not offer wildcard support. Otherwise there would be no reason for LIKE
SELECT * FROM table WHERE col RLIKE '.*'
i.e. regular-expression LIKE.
zombat's answer is great, but I only noticed in his answer that you are selecting integers. He mentioned IN() and BETWEEN(). Here's examples using those syntaxes, as well as some other options you have for an integer field.
SELECT * FROM table WHERE col = 1;
SELECT * FROM table WHERE col BETWEEN 1 AND 12;
SELECT * FROM table WHERE col BETWEEN 6 AND 12;
SELECT * FROM table WHERE col <= 6;
SELECT * FROM table WHERE col < 6;
SELECT * FROM table WHERE col >= 6;
SELECT * FROM table WHERE col > 6;
SELECT * FROM table WHERE col <> 6;
SELECT * FROM table WHERE col IN (1,2,5,6,10);
SELECT * FROM table WHERE col NOT IN (1,2,5,6,10);
Assuming your query is parameter driven a case statement is probably appropriate
select * from mytable
where col like case when #myvariable is null then % else myvariable end
Where #myvariable is either null if you dont want a value otherwise it would use the integer value you pass in.
I have encountered such a case while building a stored procedure for a report
Following is my solution, hope this is what you had in mind :)
set #p = "ALL";
Query:
select * from fact_orders
where
dim_country_id = if(#p is null or #p="ALL", dim_country_id, #p)
limit 10
;
If your values are in the the range (1,12) then:
select * from table where col>=5 and col<=5; //this is equal to col=5
select * from table where col>=0 and col<=12; //this is equal to col=any value
The same line can produce both effects by choosing the 2 parameters appropriately.
I faced a similar problem when I needed a single prepared statement which should work with 2 different ways , either checking for a particular value in a column or ignoring that column completely.

Is there an ANSI SQL alternative to the MYSQL LIMIT keyword?

Is there an ANSI SQL alternative to the MYSQL LIMIT keyword?
The LIMIT keyword limits the number of rows returned by a SELECT e.g:
SELECT * FROM People WHERE Age > 18 LIMIT 2;
returns 2 rows.
SELECT * FROM People WHERE Age > 18 LIMIT 10, 2;
returns 2 rows after the first 10.
this shows the different ways:
-- DB2
select * from table fetch first 10 rows only
-- Informix
select first 10 * from table
-- Microsoft SQL Server and Access
select top 10 * from table
-- MySQL and PostgreSQL
select * from table limit 10
-- Oracle
select * from (select * from table) where rownum <= 10
Not in SQL:1999.
There are two possible approaches you can use in later standards, with generally low levels of support in today's DBMSs.
In SQL:2008 you can use the DB/2 syntax:
SELECT * FROM things
ORDER BY smell
FETCH FIRST n ROWS ONLY
This only works for “LIMIT n” and not the extended “LIMIT m, n” offset syntax. In SQL:2003 you can use window functions, which can support the extended syntax but is a super PITA:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY smell) AS rn,
FROM things
)
WHERE rn<=n -- or rn BETWEEN m+1 AND m+n
You will more usually use the DBMS-specific methods today.
see also http://en.wikipedia.org/wiki/Select_(SQL)#FETCH_FIRST_clause
SELECT * FROM T LIMIT 10 OFFSET 20 -- Netezza, MySQL, PostgreSQL (also supports the standard, since version 8.4), SQLite, HSQLDB, H2
SELECT * from T WHERE ROWNUM <= 10 -- Oracle (also supports the standard, since Oracle8i)
SELECT FIRST 10 * from T -- Ingres
SELECT FIRST 10 * FROM T order by a -- Informix
SELECT SKIP 20 FIRST 10 * FROM T order by c, d -- Informix (row numbers are filtered after order by is evaluated. SKIP clause was introduced in a v10.00.xC4 fixpack)
SELECT TOP 10 * FROM T -- MS SQL Server, Sybase ASE, MS Access
SELECT TOP 10 START AT 20 * FROM T -- Sybase SQL Anywhere (also supports the standard, since version 9.0.1)
SELECT FIRST 10 SKIP 20 * FROM T -- Interbase, Firebird
SELECT * FROM T ROWS 20 TO 30 -- Firebird (since version 2.1)
SELECT * FROM T
WHERE ID_T > 10 FETCH FIRST 10 ROWS ONLY -- DB2
SELECT * FROM T
WHERE ID_T > 20 FETCH FIRST 10 ROWS ONLY -- DB2 (new rows are filtered after comparing with key column of table T)
I don't believe so. All the databases that I'm aware of use vendor-specific keywords for that functionality.
Adding to #jle's answer:
SQLite supports LIMIT (MySQL/PostgreSQL)
InterBase/Firebird support SELECT FIRST and SKIP (like Informix)
Also see Emulate MySQL LIMIT clause in Microsoft SQL Server 2000
HSQL/H2 uses LIMIT like MySQL
Let me link here a related SO question, with a great answer by Lukas Eder and another good answer by bobince:
How universal is the LIMIT statement in SQL?
edit: A few more good reference links, worth to look at in similar cases:
Wikipedia on limiting results and FETCH FIRST in the SELECT statement ;
"Comparison of Different SQL Implementations" on limiting the result sets ;
The jOOQ user manual page on the LIMIT clause from Lukas Eder's answer.