views:

2373

answers:

5

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.

+4  A: 

I don't believe so. All the databases that I'm aware of use vendor-specific keywords for that functionality.

Jeremy DeGroot
+6  A: 

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
jle
I've always thought it was ridiculous that Oracle makes you do a subselect to do it this way, but the rownum property is assigned prior to reordering with ORDER BY.
R. Bemrose
'oraclese' has its pros and cons eh? I do like Oracle's join shorthand (+) for an outer join...
jle
+1 nice summary! SQLite supports LIMIT, like MySQL/PostgreSQL. InterBase/Firebird support SELECT FIRST and SKIP, like Informix.
Bill Karwin
+4  A: 

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.

bobince
A: 

Adding to @jle's answer:

  • SQLite supports LIMIT (MySQL/PostgreSQL)
  • InterBase/Firebird support SELECT FIRST and SKIP (like Informix)

Also see http://stackoverflow.com/questions/216673/emulate-mysql-limit-clause-in-microsoft-sql-server-2000

Bill Karwin
A: 

HSQL/H2 uses LIMIT like MySQL

xkcd_fan