thecodex.expert · The Codex Family of Knowledge
SQL

Sorting and Limiting

Without ORDER BY, a query’s row order is not guaranteed at all — an engine is free to return rows in whatever order is fastest for it internally.

SQL:2016 / ANSI LIMIT syntax varies Last verified:
Canonical Definition

ORDER BY sorts the final result set by one or more columns, ascending (ASC, the default) or descending (DESC); sorting by multiple columns breaks ties using the later columns in order. LIMIT restricts how many rows come back, and OFFSET skips a number of rows before starting to return results — together, the standard mechanism for pagination. Syntax for this differs by engine: PostgreSQL, MySQL, and SQLite use LIMIT/OFFSET, while SQL Server uses TOP or OFFSET/FETCH, and the ANSI standard itself specifies FETCH FIRST.

ORDER BY: ASC, DESC, and multiple columns

Sorting by more than one column uses later columns as tie-breakers for rows that are equal on earlier ones.

SQLorder_by.sql
SELECT * FROM products ORDER BY price DESC;              -- highest first

SELECT * FROM employees
ORDER BY department ASC, salary DESC;    -- group by dept, highest salary first within each

LIMIT and OFFSET: capping and paginating

OFFSET skips rows before LIMIT starts counting — this exact pattern (LIMIT + OFFSET) is the most common way to implement "page 2 of results" in an application.

SQLlimit_offset.sql
-- PostgreSQL / MySQL / SQLite:
SELECT * FROM products ORDER BY price DESC LIMIT 10;              -- top 10
SELECT * FROM products ORDER BY price DESC LIMIT 10 OFFSET 20;    -- page 3, 10 per page

-- ANSI standard / SQL Server equivalent:
SELECT * FROM products ORDER BY price DESC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

Without ORDER BY, row order is not guaranteed

A common mistake is assuming rows come back in insertion order or primary-key order without an explicit ORDER BY — the SQL standard makes no such guarantee, and an engine's query planner is free to return rows in whatever sequence is most efficient for that particular execution plan, which can even change between runs of the identical query.

Sources

1
PostgreSQL Global Development Group. PostgreSQL Documentation, "Sorting Rows" and "LIMIT and OFFSET", postgresql.org/docs.