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.
The same query written three ways, depending on the engine.
Filed under Querying
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.
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.
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.
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.
SELECT name, price FROM products ORDER BY price DESC LIMIT 5;
LIMIT is the only syntax: no TOP, no FETCH.
SELECT name, price FROM products ORDER BY price DESC LIMIT 5;
LIMIT is the only syntax: no TOP, no FETCH.
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.
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.
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.
Five engines, two spellings of "give me rows 21 to 30", plus Oracle's old ROWNUM wrapper.
One window-function query that runs everywhere, plus PostgreSQL's DISTINCT ON shortcut for one row per group.
Three engines support the keywords; two need a sort-key trick.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.