skip to content

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 (either way)3 pages
page 51, OFFSET20 pages
page 251, OFFSET94 pages
page 501, OFFSET186 pages
page 1,001, OFFSET367 pages
page 51, keyset3 pages
page 251, keyset3 pages
page 501, keyset4 pages
page 1,001, keyset4 pages
real output, postgres 18.6 (PGlite 0.5.12) · keyset
pages read for one page of 20 events, at five depths, from the capture. OFFSET grows with the page number; keyset stays flat.

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:

sqldb=events · session ks
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;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · EXPLAIN
Limit (actual rows=20.00 loops=1) Buffers: shared hit=73 read=21 -> Index Scan using events_at_id on events (actual rows=5020.00 loops=1) Index Searches: 1 Buffers: shared hit=73 read=21 Planning: Buffers: shared hit=65 read=6

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):

idint8kindtextoccurred_attimestamptz
5000view2026-03-19 04:45:52+00
5001click2026-03-19 04:49:10+00
5002click2026-03-19 04:53:53+00
(3 rows)
real output, postgres 18.6 (PGlite 0.5.12) · keyset
the rows on either side of the boundary between page 250 and page 251. the cursor is the last row of the page before: its occurred_at and its id.

so the next page is everything after ('2026-03-19 04:45:52+00', 5000), in order, 20 of it:

sqldb=events · session ks
continues session ks (1 earlier block run first)
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;
output, from postgres 18.6
EXPLAIN
Limit (actual rows=20.00 loops=1) Buffers: shared hit=3 -> Index Scan using events_at_id on events (actual rows=20.00 loops=1) Index Cond: (ROW(occurred_at, id) > ROW('2026-03-19 04:45:52+00'::timestamp with time zone, 5000)) Index Searches: 1 Buffers: shared hit=3

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 =
SELECT id, user_id, kind, occurred_at FROM events ORDER BY occurred_at, id LIMIT 20 OFFSET 5000
pages read by the whole query (Buffers: shared hit + read)
94 pages
3 pages
94 pages

page 251 by OFFSET: read 5,020 rows, return the last 20.

real output, postgres 18.6 (PGlite 0.5.12) · keyset
page 251 three ways. the row comparison is one 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.
predict the output
the OR version is logically the same as the row comparison. why is it slow?
sql
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_at alone 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) for ORDER BY occurred_at, id and (occurred_at, id) > (…). for newest first, flip all three: ORDER BY occurred_at DESC, id DESC with (occurred_at, id) < (…); the same index serves it backwards.
  • mixed directions don't fit a row comparison. ORDER BY score DESC, id ASC can'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_at and id (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.