SQL ORDER BY, LIMIT and OFFSET: Sort and Page Results
Without ORDER BY, a database may return rows in any order it finds convenient, and that order can change as data grows. Whenever order matters, and it almost always does for what people see, say so explicitly.
Sorting
ORDER BY price sorts ascending (smallest first), which is the default and can be written ASC. ORDER BY price DESC sorts descending. Text sorts alphabetically; in SQLite the default comparison is by character code, so uppercase letters come before lowercase ones. Add COLLATE NOCASE to sort without regard to case.
You can sort by several columns: ORDER BY genre, title sorts by genre first, and uses title only to order books within the same genre. Each column can have its own direction, as in ORDER BY genre ASC, price DESC. You can also sort by an expression or by a column alias from the SELECT list.
Top-N with LIMIT
ORDER BY price DESC LIMIT 3 answers "what are the three most expensive books?" in one step. LIMIT without ORDER BY just returns some rows, which is fine for peeking but not for answering a question.
Expected output
title | price Northern Lights Code | 39.5 Small Data, Big Ideas | 34.99 Learning SQL by Doing | 29.0 genre | title Fiction | The Last Lantern Fiction | The Quiet Harbor Nonfiction | Desert Gardens Nonfiction | Kitchen Chemistry
Paging with OFFSET
LIMIT 4 OFFSET 2 skips the first two rows of the sorted result, then returns the next four. Web pages use this for "page 2, page 3" listings: page n of size s is LIMIT s OFFSET (n - 1) * s. On very large tables, big offsets become slow, because the database still has to step over every skipped row; production systems often use "keyset" paging instead, such as WHERE id > :last_seen_id ORDER BY id LIMIT 20.
Where NULLs go
When a sort column contains NULL, SQLite treats NULL as smaller than any other value, so NULLs come first in ascending order and last in descending order. Other databases differ, and SQLite also supports NULLS FIRST and NULLS LAST to make the choice explicit.
Ties
If two rows have the same sort value, their relative order is not guaranteed. Add a second, unique column such as id to make the order stable, which matters for paging: without it, a row could appear on two pages or on none.
Common mistakes
- Relying on the "natural" order of a table.
- Putting
LIMITbeforeORDER BY; the clauses must appear asWHERE, thenORDER BY, thenLIMIT. - Paging without a unique tie-breaker column.
Summary
ORDER BY col [ASC|DESC]sorts results; several columns sort within ties.LIMIT nreturns at most n rows;OFFSET mskips m rows first.- Add a unique column to the sort to make paging stable.
Quiz: ORDER BY and LIMIT