keyset pagination
OFFSET 100000 reads 100,000 rows to throw them away. WHERE (a, b) > (x, y) doesn't.
- address
- everything.indexes.keyset_pagination
- part
- part 8, indexes, from the outside
- chapter
- chapter 8 of 12
- reading time
- 7 min
LIMIT 20 OFFSET 5000 makes postgres produce 5,020 rows and throw 5,000 of them away. the deeper the page, the slower it gets. keyset pagination remembers where the last page ended and asks for what comes after it: WHERE (occurred_at, id) > (last_at, last_id). with an index on (occurred_at, id) that's one descent and 20 rows, on page 1 or page 1,001.
the picture
you know how a bookmark works? you don't count 251 pages from the front every time you pick the book up. you open it where you left off. OFFSET is counting from the front. keyset is the bookmark: the last row you saw.
page 1,001 by OFFSET read 367 pages to return 20 rows. by keyset, 4. and that's on a 25,000-row table in memory; on a big table on disk, deep OFFSET pages are the slow query in the log that only happens when a crawler walks your pagination.
why OFFSET is slow
OFFSET isn't a seek. postgres has no way to jump to "the 5,001st row" of a result: rows are numbered only as they come out of the plan. so it runs the query, counts rows off one by one, discards the first 5,000, and keeps the next 20:
CREATE INDEX events_at_id ON events (occurred_at, id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, kind, occurred_at FROM events
ORDER BY occurred_at, id
LIMIT 20 OFFSET 5000;the Index Scan says actual rows={fmt(scanned(2))}. every one of those was fetched, heap page and all, so the Limit node could skip it. the index made the order free, but not the skipping. (LIMIT and OFFSET has the semantics.)
keyset: start after the last row
the page before page 251 ended on this row (the first two of page 251 under it):
| idint8 | kindtext | occurred_attimestamptz |
|---|---|---|
| 5000 | view | 2026-03-19 04:45:52+00 |
| 5001 | click | 2026-03-19 04:49:10+00 |
| 5002 | click | 2026-03-19 04:53:53+00 |
so the next page is everything after ('2026-03-19 04:45:52+00', 5000), in order, 20 of it:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, user_id, kind, occurred_at FROM events
WHERE (occurred_at, id) > ('2026-03-19 04:45:52+00', 5000)
ORDER BY occurred_at, id
LIMIT 20;Index Cond: (ROW(occurred_at, id) > ROW(...)): the whole comparison is an index search. one descent to the cursor, then 20 entries forward. the cost doesn't depend on how deep the page is, because nothing before the cursor is ever read.
the row comparison is the trick
(a, b) > (x, y) is a row comparison, standard SQL: it means a > x OR (a = x AND b > y), compared left to right like words in a dictionary. that's exactly the order of an index on (a, b), so postgres can turn it into a single starting point in the index. write the same thing out longhand and it can't:
page 251 by OFFSET: read 5,020 rows, return the last 20.
Index Cond: 3 pages. the same condition written with OR becomes a Filter on a scan that starts at the very first entry: 5,000 rows removed, 94 pages, no better than OFFSET.WHERE occurred_at > '2026-03-19 04:45:52+00'
OR (occurred_at = '2026-03-19 04:45:52+00' AND id > 5000)the rules
- the ORDER BY needs a tiebreaker that makes it unique.
occurred_atalone could have two events in the same second, and then "after the last one" would skip or repeat rows at the page boundary. ending on the primary key (id) fixes it, and the cursor carries both. - the index matches the ORDER BY and the comparison:
(occurred_at, id)forORDER BY occurred_at, idand(occurred_at, id) > (…). for newest first, flip all three:ORDER BY occurred_at DESC, id DESCwith(occurred_at, id) < (…); the same index serves it backwards. - mixed directions don't fit a row comparison.
ORDER BY score DESC, id ASCcan't be written as one(a, b) > (x, y). either use the OR form with an index declared(score DESC, id)and accept a filter, or put the columns in one direction. - the cursor travels with the page. the client sends back the last row's
occurred_atandid(often encoded into an opaque "next" token), not a page number.
what you give up
you can't jump to page 251 directly; you can only go forward (or backward, flipping the comparison) from where you are. that's why infinite scroll, "load more" buttons and API cursors use keyset, and numbered page links use OFFSET. for numbered pages deep in a big result, people usually cap the depth, or precompute the page boundaries.
and a page can shift under you with OFFSET: if a row is inserted near the front between two requests, every later page moves by one, and you see a row twice. with keyset, page boundaries are values, not positions, so new rows before the cursor don't move what comes after it.
keylines
- OFFSET n reads n rows and throws them away. deep pages get linearly slower.
- keyset: WHERE (a, id) > (last_a, last_id), with an index on (a, id).
- one index descent and n rows, on any page.
- write the row comparison, not the OR: only the row form becomes an index range.
- keyset can't jump to page k. it goes forward from a cursor.