// dialect comparison

Row paging: LIMIT, TOP, OFFSET-FETCH and ROWNUM

Five engines, two spellings of "give me rows 21 to 30", plus Oracle's old ROWNUM wrapper.

Filed under Querying

The verdict

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.

Where they differ

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.

How each engine writes it

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.

PostgreSQL

SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;

The standard OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY works too.

MySQL

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.

SQLite

SELECT id, name FROM customers ORDER BY id LIMIT 10 OFFSET 20;

Also accepts the MySQL-style LIMIT 20, 10. No FETCH syntax.

Oracle

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.

Questions that come up

Do I need an ORDER BY to page?

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.

How do I page on old Oracle versions?

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.

Is deep paging slow?

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.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.