Skip to content

SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause

Sometimes you want only the first few rows of a result: the three largest invoices, or the ten most recent orders. Every database can do this, but they spell it differently, and this is one of the places where SQL dialects disagree most.

The examples use the Productions table from the example database.

Each version below returns the same three rows:

Title Budget
The Lantern Keepers 18,500,000
Six Bells 11,000,000
Quarry Lane 7,200,000

MySQL, PostgreSQL and SQLite add LIMIT at the end:

SELECT Title, Budget
FROM Productions
ORDER BY Budget DESC
LIMIT 3;

SQL Server and Microsoft Access put TOP straight after SELECT:

SELECT TOP 3 Title, Budget
FROM Productions
ORDER BY Budget DESC;

Oracle 12c and later, PostgreSQL and Db2 accept the SQL standard’s wording, FETCH FIRST:

SELECT Title, Budget
FROM Productions
ORDER BY Budget DESC
FETCH FIRST 3 ROWS ONLY;

SQL Server supports the standard form too, but only with an OFFSET before it: ORDER BY Budget DESC OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY.

Older versions of Oracle have none of these, and filter on ROWNUM, the position of each row as it is read. Because ROWNUM is given out before any sorting, the sort has to happen first, in a subquery:

SELECT *
FROM (SELECT Title, Budget FROM Productions ORDER BY Budget DESC)
WHERE ROWNUM <= 3;

Filtering happens before the limit, so the limit counts only the rows that pass. The two smallest UK budgets:

SELECT Title, Budget
FROM Productions
WHERE Country = 'UK'
ORDER BY Budget
LIMIT 2;
Title Budget
Quarry Lane 7,200,000
Six Bells 11,000,000

SQL Server and Access can return a share of the rows rather than a fixed number, as in SELECT TOP 50 PERCENT …. Oracle’s version is FETCH FIRST 50 PERCENT ROWS ONLY.