Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 972
Gary Willoughby Avatar asked Feb 27 '09 15:02

Gary Willoughby


People also ask

What can I use instead of limit in MySQL?

To get only the specified rows from the table, MySQL uses the LIMIT clause, whereas SQL uses the TOP clause, and Oracle uses the ROWNUM clause with the SELECT statement.

Is ANSI SQL same as MySQL?

MySQL server supports instead the ANSI SQL syntax INSERT INTO ... SELECT ..., which is basically the same thing. See Section 6.4. 3.1.

Is limit supported by MySQL?

MySQL has hard limit of 4096 columns per table, but the effective maximum may be less for a given table. The exact column limit depends on several factors: The maximum row size for a table constrains the number (and possibly size) of columns because the total length of all columns cannot exceed this size.

Is there limit in SQL?

This issue occurs because SQL Server limits the number of identifiers and constants that can be contained in a single expression of a query. This limit is 65,535.


2 Answers

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 
like image 75
jle Avatar answered Sep 20 '22 12:09

jle


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.

like image 32
bobince Avatar answered Sep 18 '22 12:09

bobince