ORDER BY and LIMIT: sorting and paging
Sorting makes a result readable and makes "the top few" answerable. LIMIT decides how large that answer is.
Order is never implied
A SQL table has no order. Without ORDER BY the database returns rows in whatever order is convenient, which can change between runs of the same query. Never read a result as if the screen order meant something.
Add a column and ASC (default) or DESC. Several comma-separated keys break ties: date descending, then revenue descending within a date.
SELECT order_id, order_date, revenue
FROM orders
ORDER BY order_date DESC, revenue DESC
LIMIT 10;
Where NULLs land
SQLite treats NULL as the smallest value, so ascending order puts NULLs first and descending puts them last. To force them to the end either way, sort on (col IS NULL) first, then on col.
Sort keys can be expressions: ROUND(revenue) or LENGTH(customer_id) avoids creating a column just to sort by it.
| Sort expression | Result | Use |
|---|---|---|
| ORDER BY revenue DESC | largest first | top revenue |
| ORDER BY 1 | by the first SELECT column | short queries |
| ORDER BY (x IS NULL), x | NULLs last | cleaning blank values |
| ORDER BY revenue DESC LIMIT 5 | five largest | Top-N |
LIMIT and OFFSET
LIMIT n keeps the first n rows; OFFSET m skips m. Paging combines them as LIMIT 20 OFFSET 40. Large offsets are slow because the database still counts the skipped rows.
Without a fully determined order, OFFSET paging can repeat or drop rows between pages. Always end the sort key with a unique column such as order_id.
SELECT order_id, order_date, revenue
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 20 OFFSET 40;
Top-N inside each group
LIMIT gives the global top ten, not the top three per channel. Use ROW_NUMBER() OVER (PARTITION BY channel ORDER BY revenue DESC), then filter rn <= 3 in the outer query.
SELECT * FROM (
SELECT channel, order_id, revenue,
ROW_NUMBER() OVER (PARTITION BY channel ORDER BY revenue DESC) AS rn
FROM orders
) WHERE rn <= 3;
Write the sort order down
When reporting a top list, state the sort and the tie-break: "top ten by revenue descending, order id ascending on ties". The next person can then reproduce the same list.
Questions
Does LIMIT alone give a stable result?
No. Without ORDER BY nothing guarantees which rows are cut. Pair LIMIT with a sort.
Why is deep OFFSET paging slow?
OFFSET counts and discards the skipped rows. Keyset pagination, filtering on the last key you saw, is faster.
Sources
Every query in this guide runs against the built-in sample data.
Open the lab