Part 18 / Topic 3 of 7
Pagination at scale
LIMIT 20 OFFSET 150000 looks innocent and does something brutal — see the actuals:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders ORDER BY id OFFSET 150000 LIMIT 20;
QUERY PLAN
-----------------------------------------------------------------------------------
Limit (actual rows=20 loops=1)
-> Index Scan using big_orders_pkey on big_orders (actual rows=150020 loops=1)
(2 rows)
The Limit returns 20 rows — after its child fetched 150,020 and threw 150,000 away. Every page deeper repeats all the work before it; page 7,500 costs 7,500 pages' worth. Keyset pagination remembers where the last page ended and starts there:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM big_orders WHERE id > 150000 ORDER BY id LIMIT 20;
QUERY PLAN
-------------------------------------------------------------------------------
Limit (actual rows=20 loops=1)
-> Index Scan using big_orders_pkey on big_orders (actual rows=20 loops=1)
Index Cond: (id > 150000)
(3 rows)
Twenty rows fetched, twenty returned — page 7,500 costs the same as page 1. The contract: pages are reached by cursor ("after id 150000"), not by number, and the ORDER BY needs a unique tiebreaker (ORDER BY created_at, id with WHERE (created_at, id) > ($1, $2) for non-unique sorts — row comparison syntax, made for this). OFFSET stays fine for shallow paging — page 3 of a dashboard — and nowhere else.
🧪 Quick quiz — answer from memory, then check.
- Why does OFFSET get slower with depth?
- What does keyset pagination require of the ORDER BY?
Show the answers
- The rows before the offset are still fetched (in order) and discarded — work proportional to depth.
- A deterministic, unique ordering — add the key as tiebreaker — and passing the last row's values as the next page's cursor.
Done here? The practice set for Part 18 — 5 exercises with solutions — is on the part page.