🐘 PostgreSQL
Beginner
How do you sort query results in PostgreSQL?
Answer
Use ORDER BY at the end of a query. ORDER BY column ASC sorts ascending (default); ORDER BY column DESC sorts descending. Multiple columns: ORDER BY last_name ASC, first_name ASC. Sort by expression: ORDER BY LENGTH(name). Sort by alias: SELECT name AS n FROM users ORDER BY n. NULLS FIRST / NULLS LAST controls where NULLs appear (PostgreSQL-specific extension): ORDER BY score DESC NULLS LAST. Without ORDER BY, row order is not guaranteed — never rely on implicit ordering. For pagination, combine with LIMIT and OFFSET: ORDER BY id LIMIT 20 OFFSET 40.