Sub topic 14
TOP, FETCH FIRST, and Other Dialect Syntax
LIMIT and OFFSET are not part of the SQL standard, so the syntax you have used so far works in some databases and fails in others. This chapter maps the same row-limiting ideas onto the dialects you are likely to meet.
This chapter assumes you know basic SELECT, WHERE, and ORDER BY. It also assumes you have used LIMIT and OFFSET for paging, and you know why a deterministic sort matters.
The problem: one idea, several spellings
Every major database can return "only the first N rows" and "skip M rows first". The keywords differ. Moving a query between systems usually means rewriting this one clause, and nothing else changes.
| Database | First N rows | Skip M, then take N |
|---|---|---|
| PostgreSQL | `LIMIT n` or `FETCH FIRST n ROWS ONLY` | `LIMIT n OFFSET m` or `OFFSET m ROWS FETCH NEXT n ROWS ONLY` |
| MySQL / MariaDB | `LIMIT n` | `LIMIT n OFFSET m` or `LIMIT m, n` |
| SQLite | `LIMIT n` | `LIMIT n OFFSET m` |
| SQL Server | `TOP (n)` or `FETCH` | `OFFSET m ROWS FETCH NEXT n ROWS ONLY` |
| Oracle 12c and later | `FETCH FIRST n ROWS ONLY` | `OFFSET m ROWS FETCH NEXT n ROWS ONLY` |
| Older Oracle (before 12c) | `ROWNUM` filter | nested subquery with `ROWNUM` |
The standard form is OFFSET ... FETCH. The LIMIT form is a popular extension that PostgreSQL, MySQL, and SQLite share.
The standard form: OFFSET and FETCH
The SQL standard defines row limiting with OFFSET and FETCH. This is the portable choice if you must support several engines. The following query is the standard equivalent of LIMIT 10 OFFSET 20:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;It runs on PostgreSQL, Oracle 12c and later, and SQL Server 2012 and later. Some details matter:
OFFSETcomes beforeFETCH. This is the reverse ofLIMIT n OFFSET m, where the count is written first.FIRSTandNEXTare interchangeable, as areROWandROWS. WritingFETCH FIRST 1 ROW ONLYreads more naturally thanFETCH NEXT 1 ROWS ONLY, but both are valid.ONLYcan be replaced withWITH TIESin engines that support it.WITH TIESalso returns rows that tie with the last row on theORDER BYkey, so you can get more than N rows.- SQL Server requires
ORDER BYwhenever you useOFFSET. Other engines allow it without one, but the result is then unpredictable.
If you only need the first rows and no skipping, drop the OFFSET part:
SELECT order_id, order_date, total
FROM orders
ORDER BY total DESC
FETCH FIRST 3 ROWS ONLY;WITH TIES
Suppose you want the three most expensive orders, and the third and fourth orders have the same total. ONLY cuts arbitrarily between them. WITH TIES keeps both.
SELECT order_id, total
FROM orders
ORDER BY total DESC
FETCH FIRST 3 ROWS WITH TIES;This form needs an ORDER BY, because ties are defined by the sort key. PostgreSQL 13 and later, Oracle 12c and later, and SQL Server (through TOP (3) WITH TIES) support it. MySQL and SQLite do not.
LIMIT in PostgreSQL, MySQL, and SQLite
These three engines accept the form you already know:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;MySQL and MariaDB also accept a shorthand with a comma:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 20, 10;In the comma form the offset comes first and the count second. That order is the opposite of what many people expect, so prefer LIMIT 10 OFFSET 20. SQLite also accepts the comma form, with the same meaning.
Two further points:
- In SQLite and MySQL,
OFFSETis only valid afterLIMIT. In PostgreSQL you can writeOFFSETalone, or putOFFSETbeforeLIMIT. - A negative
LIMITis an error in PostgreSQL and MySQL. SQLite treats a negative limit as "no limit", which is sometimes used to writeLIMIT -1 OFFSET 20to skip rows with no cap.
TOP in SQL Server
SQL Server has long used TOP, which goes directly after SELECT:
SELECT TOP (5) order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC;TOP has several features and limits:
- The parentheses are recommended. They are required when the count is an expression or variable, and optional only for a plain integer literal.
TOP (n) PERCENTreturns a share of the rows, for exampleTOP (10) PERCENT.TOP (n) WITH TIESincludes tied rows, and it requiresORDER BY.TOPcannot skip rows. For paging you needOFFSET ... FETCH.TOPandOFFSETcannot be used together in the same query level.
Placing TOP next to DISTINCT is a common stumbling block. The order is SELECT DISTINCT TOP (5) ..., with DISTINCT first:
SELECT DISTINCT TOP (5) country
FROM customers
ORDER BY country;SQL Server removes duplicates, sorts the unique values, and then keeps five. This matches the evaluation order from the earlier chapters: DISTINCT runs before ORDER BY, and the row cap runs last.
Oracle before 12c: ROWNUM
Older Oracle versions had no row-limiting clause. They exposed a pseudo-column called ROWNUM, which numbers rows as they are produced. The trap is that ROWNUM is assigned before ORDER BY runs, so this query does not return the top five:
SELECT order_id, order_date, total
FROM orders
WHERE ROWNUM <= 5
ORDER BY order_date DESC;It picks five arbitrary rows and then sorts only those five. The fix is to sort in a subquery and filter outside it:
SELECT order_id, order_date, total
FROM (
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
)
WHERE ROWNUM <= 5;For an offset, the pattern needs a second level that captures ROWNUM under an alias. On Oracle 12c and later, use OFFSET ... FETCH instead.
Translating a query
The most reliable approach is to pick the standard form when you can and translate in a fixed order. The diagram shows the decision.
Here is one query written for three targets. The task is the second page of the five most recent orders, with five rows per page.
-- PostgreSQL, MySQL, SQLite
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5 OFFSET 5;-- SQL Server 2012+ and Oracle 12c+
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
OFFSET 5 ROWS
FETCH NEXT 5 ROWS ONLY;-- SQL Server, first page only
SELECT TOP (5) order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC;The ORDER BY clause stays identical in all three. Only the limiting clause changes.
Gotchas when moving queries
- Parameters. Some drivers do not allow a bind parameter for
LIMITorTOP. SQL Server acceptsTOP (@n), and PostgreSQL acceptsLIMIT $1. Check your driver if a placeholder is rejected. - No ORDER BY. Every dialect will run the query, and most will return rows in an arbitrary order. A query that "worked" on one engine can return different rows on another.
- Keyset pagination. The
WHERE (order_date, order_id) < (...)row-value comparison works in PostgreSQL, MySQL, and SQLite 3.15 and later. SQL Server and Oracle do not support it, so write the condition out asorder_date < @d OR (order_date = @d AND order_id < @id). Combine it withTOPorFETCH FIRSTand noOFFSET. - Large offsets stay slow. A different syntax does not fix the cost of skipping rows.
OFFSET 100000 ROWSstill reads and discards 100,000 rows in every engine. - Version support.
FETCH FIRSTarrived in PostgreSQL 8.4, in SQL Server 2012 asOFFSET ... FETCH, and in Oracle 12c. Check the server version before you rely on it.
Summary of rules
LIMIT n OFFSET mworks in PostgreSQL, MySQL, MariaDB, and SQLite.OFFSET m ROWS FETCH NEXT n ROWS ONLYis the standard form and works in PostgreSQL, SQL Server 2012+, and Oracle 12c+.TOP (n)is SQL Server only, and it cannot skip rows.ROWNUMneeds a subquery so that sorting happens before numbering.- Always keep a deterministic
ORDER BY, whatever the syntax.
Exercise
Rewrite this MySQL query for SQL Server 2012 or later so that it returns the same rows: SELECT order_id, total FROM orders ORDER BY total DESC, order_id DESC LIMIT 10 OFFSET 30;
Show answer
SELECT orderid, total FROM orders ORDER BY total DESC, orderid DESC OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY; The ORDER BY stays the same and is required by SQL Server. OFFSET comes first, then FETCH NEXT with the count. TOP cannot be used because it cannot skip rows.
Exercise
An old Oracle 11g query is SELECT order_id, total FROM orders WHERE ROWNUM <= 3 ORDER BY total DESC;. It does not return the three largest totals. Why not, and how do you fix it?
Show answer
ROWNUM is assigned before ORDER BY runs, so the query takes three arbitrary rows and then sorts only those. Move the sort into a subquery, then filter on ROWNUM in the outer query: SELECT orderid, total FROM (SELECT orderid, total FROM orders ORDER BY total DESC, order_id DESC) WHERE ROWNUM <= 3;
Exercise
Your top three totals are 900, 800, 800, and a fourth order also has total 800. Which query returns all of the 800 orders, and in which engines does it work?
Show answer
Use FETCH FIRST 3 ROWS WITH TIES after ORDER BY total DESC. It returns the 900 order and every order tied at 800. It works in PostgreSQL 13+ and Oracle 12c+. In SQL Server, the equivalent is SELECT TOP (3) WITH TIES with ORDER BY. MySQL and SQLite do not support it.