// dialect comparison

First N rows: TOP vs LIMIT vs FETCH FIRST

The same query written three ways, depending on the engine.

Filed under Querying

The verdict

LIMIT covers PostgreSQL, MySQL and SQLite; FETCH FIRST is the standard and covers PostgreSQL and Oracle; TOP is SQL Server only. Ties are where they differ most: SQL Server has TOP … WITH TIES, PostgreSQL 13+ and Oracle have FETCH FIRST … WITH TIES, and MySQL and SQLite need a RANK() subquery.

Where they differ

A TOP-N query is an ORDER BY plus a row cap. SQL Server puts TOP before the column list, MySQL/SQLite/PostgreSQL put LIMIT after the query, and the SQL standard spelling is FETCH FIRST … ROWS ONLY.

How each engine writes it

SQL Server

SELECT TOP 5 name, price FROM products ORDER BY price DESC;

TOP 5 WITH TIES also returns rows tied with the fifth. OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY works too, but T-SQL has no FETCH … WITH TIES.

PostgreSQL

SELECT name, price FROM products ORDER BY price DESC LIMIT 5;

FETCH FIRST 5 ROWS ONLY also works, and FETCH FIRST 5 ROWS WITH TIES since PostgreSQL 13.

MySQL

SELECT name, price FROM products ORDER BY price DESC LIMIT 5;

LIMIT is the only syntax: no TOP, no FETCH.

SQLite

SELECT name, price FROM products ORDER BY price DESC LIMIT 5;

LIMIT is the only syntax: no TOP, no FETCH.

Oracle

SELECT name, price FROM products ORDER BY price DESC FETCH FIRST 5 ROWS ONLY;

12c+. Before 12c: SELECT * FROM (… ORDER BY price DESC) WHERE ROWNUM <= 5.

Questions that come up

Why does my TOP-N query return different rows every run?

ORDER BY price DESC leaves rows with equal prices in no particular order, so the engine can hand back any of them for the last slots. Add a unique tiebreaker: ORDER BY price DESC, id.

How do I include rows tied with fifth place?

SQL Server: TOP 5 WITH TIES. PostgreSQL 13+ and Oracle 12c+: FETCH FIRST 5 ROWS WITH TIES. MySQL 8.0+ and SQLite have no WITH TIES; rank in a subquery and filter outside it, because window functions are not allowed in WHERE: SELECT name, price FROM (SELECT name, price, RANK() OVER (ORDER BY price DESC) AS rk FROM products) r WHERE rk <= 5.

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.