Skip to the page

Performance · mid

Pagination: OFFSET vs keyset

OFFSET pagination makes the database read and discard all skipped rows and shifts when rows are inserted, while keyset (seek) pagination filters for rows after the last one seen using the sort columns, which stays fast with a matching index and never repeats rows.

The notes

What you must know

  • OFFSET n: the database still produces the first n rows and throws them away, so deep pages get slower; inserts between requests shift rows, causing duplicates or skips.
  • Keyset: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20, with an index on (created_at, id). Row-value comparison is supported by Postgres (and SQLite); MySQL evaluates it but may not use the index, so write the expanded form there.
  • The ORDER BY must be deterministic: add a unique tiebreaker (id), and use the same columns in the index.
  • Keyset cannot jump to page 37; it fits infinite scroll and 'next/previous', which is most product UIs.
  • COUNT(*) on big Postgres tables is slow (it must check row visibility); use estimates (pg_class.reltuples) or 'has more' (fetch limit + 1).
  • ORMs: avoid N+1 while paging (load relations with the page in one batched query).

The red pen

Common traps: mistake → fix

  • Mistake: OFFSET is fine because LIMIT is small

    Fix: the cost is in the skipped rows, not the returned ones.

  • Mistake: ORDER BY created_at is enough for keyset

    Fix: equal timestamps make pages skip or repeat rows; add id.

Easy to hard

Questions interviewers ask, easy to hard

  1. How would you paginate a 10-million-row table?
  2. Why does OFFSET get slow, and why can it repeat rows?
  3. Write the keyset query for 'newest first'. Which index does it need?
  4. How do you show a total count cheaply?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview