SQL Server
SELECT id, name FROM customers ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
No LIMIT. OFFSET … FETCH is part of the ORDER BY clause in T-SQL, so leaving out ORDER BY is a syntax error.
Five engines, two spellings of "give me rows 21 to 30", plus Oracle's old ROWNUM wrapper.
Filed under Querying
LIMIT … OFFSET is the shortest and covers three engines; OFFSET … FETCH is the standard and covers SQL Server, Oracle and PostgreSQL. No single spelling runs on all five, so this is one clause a portable query layer has to generate per engine. The real trap is pre-12c Oracle, where ROWNUM applied in the same query as ORDER BY numbers the rows before they are sorted.
Paging pairs an ORDER BY with a row-range clause. PostgreSQL, MySQL and SQLite use LIMIT … OFFSET; SQL Server (2012+) and Oracle (12c+) use the standard OFFSET … FETCH, which PostgreSQL also accepts. Oracle before 12c needs a ROWNUM subquery.
SELECT id, name FROM customers ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
No LIMIT. OFFSET … FETCH is part of the ORDER BY clause in T-SQL, so leaving out ORDER BY is a syntax error.
SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;
The standard OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY works too.
SELECT id, name FROM customers ORDER BY id LIMIT 20, 10;
LIMIT offset, count. LIMIT 10 OFFSET 20 also works; there is no FETCH syntax.
SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;
Also accepts the MySQL-style LIMIT 20, 10. No FETCH syntax.
SELECT id, name FROM customers ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
12c+. Before 12c, number a sorted subquery with ROWNUM and filter the outer query.
SQL Server requires one: OFFSET … FETCH without ORDER BY is a syntax error. The other four accept a page of an unordered result, but without a sort the engine may return different rows for the same page on every run. Order by a unique key so pages neither overlap nor skip rows.
Sort in the innermost query, apply ROWNUM one level up, and filter the low end outside: SELECT * FROM (SELECT t.*, ROWNUM rn FROM (SELECT id, name FROM customers ORDER BY id) t WHERE ROWNUM <= 30) WHERE rn > 20. ROWNUM is assigned before ORDER BY runs, which is why it can't sit in the same query as the sort.
Yes, on every engine: OFFSET 100000 still reads and throws away 100,000 rows. For large result sets use keyset paging: remember the last id you showed and ask for WHERE id > :last_seen ORDER BY id with a limit of 10.
The same query written three ways, depending on the engine.
One window-function query that runs everywhere, plus PostgreSQL's DISTINCT ON shortcut for one row per group.
One portable window function, and two Oracle and SQLite features that look similar but do something else.
ORDER BY random() works on every engine and gets slower with every row you add.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.