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.
The three largest budgets
Section titled “The three largest budgets”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, BudgetFROM ProductionsORDER BY Budget DESCLIMIT 3;SQL Server and Microsoft Access put TOP straight after SELECT:
SELECT TOP 3 Title, BudgetFROM ProductionsORDER BY Budget DESC;Oracle 12c and later, PostgreSQL and Db2 accept the SQL standard’s wording, FETCH FIRST:
SELECT Title, BudgetFROM ProductionsORDER BY Budget DESCFETCH 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;With a WHERE clause
Section titled “With a WHERE clause”Filtering happens before the limit, so the limit counts only the rows that pass. The two smallest UK budgets:
SELECT Title, BudgetFROM ProductionsWHERE Country = 'UK'ORDER BY BudgetLIMIT 2;| Title | Budget |
|---|---|
| Quarry Lane | 7,200,000 |
| Six Bells | 11,000,000 |
A percentage of the rows
Section titled “A percentage of the rows”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.