SQLSQL
BeginnerLesson 3 of 15

ORDER BY, LIMIT & OFFSET – SQL

Sorting results, fetching the first n rows, and paging.

Without ORDER BY, the order of the result rows is not guaranteed – even if it happens to look stable. Always sort explicitly. ASC (ascending) is the default, DESC is descending. Multiple criteria are evaluated in sequence.

SELECT name, preis FROM produkte ORDER BY preis DESC;
SELECT name, kategorie, preis FROM produkte ORDER BY kategorie ASC, preis DESC;
SELECT name, preis FROM produkte ORDER BY 2;   -- by the 2nd column (shorthand, not recommended)

LIMIT n restricts the number of rows, OFFSET m skips the first m rows – together they give you pagination. LIMIT exists in PostgreSQL, MySQL, and SQLite; the SQL standard (also supported by PostgreSQL) has FETCH FIRST n ROWS ONLY, and SQL Server uses TOP n.

SELECT name, preis FROM produkte ORDER BY preis DESC LIMIT 3;            -- top 3 most expensive
SELECT name, preis FROM produkte ORDER BY preis DESC LIMIT 2 OFFSET 2;  -- page 2 (2 entries each)
SELECT name, preis FROM produkte ORDER BY preis DESC FETCH FIRST 3 ROWS ONLY;  -- standard SQL (PostgreSQL)
WarningOFFSET becomes slow with large values because the database still computes all the skipped rows. For long lists, use keyset pagination: WHERE id > :last_id ORDER BY id LIMIT 20.
TipWhere do NULL values go? PostgreSQL sorts them at the end for ASC, MySQL and SQLite at the beginning. NULLS FIRST / NULLS LAST (PostgreSQL, SQLite from 3.30) makes it explicit.