Backend Case Studies

Topic B3

Pagination: offset vs cursor

Why deep pages get slower with OFFSET, and why cursors don't.

9 min · intermediate

Watch: the first way reads and throws away every row before the page you asked for. The second jumps straight there.

id1234567891011121314151617181920
  • finished / the result
  • no longer used
Step 1 of 5

Page 4: ORDER BY id LIMIT 4 OFFSET 12. The database can't jump to row 13; it has to count from the start.

OFFSET counts from the start every time. A cursor remembers where the last page stopped and jumps there through the index.

Why OFFSET gets slower

OFFSET 40000 doesn't mean "jump to row 40,001". The database can't know where that row is without counting. It reads 40,000 rows, discards them, then sends the next 20. Like reading a book from page 1 every time you want to carry on from page 400. Page one is fast; page 2,000 takes seconds.

The second problem: shifting data

A user opens page 1 of a feed (newest first). While they read, 3 new posts arrive. They open page 2 with OFFSET 20, but every row has now shifted 3 places. The last three posts from page 1 show up again at the top of page 2. If something is deleted, the opposite happens: rows are skipped and never shown. A cursor doesn't have this problem, because it asks "after post X", not "after 20 rows".

Code, for programmersOffset and cursor
-- offset: slower the deeper you go, shifts when data changes
SELECT * FROM posts ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40000;

-- cursor: the client sends back the last (created_at, id) it saw
SELECT * FROM posts
WHERE (created_at, id) < ('2026-11-20 10:15:00', 98231)
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- needs: CREATE INDEX ON posts (created_at DESC, id DESC);

Note id as the tie-breaker. Two posts can share the exact same created_at; without a unique column, the cursor can skip one of them (see the sort stability topic).

When to use which

OFFSETCursor
Jump to page 37YesNo
Deep pagesSlowJust as fast
Data changing while pagingRows repeat or vanishSafe
Good forsmall admin tablesfeeds, infinite scroll, public APIs, exports

Quiz

  1. LIMIT 20 OFFSET 100000. Roughly how many rows does the database read?

  2. Why does an OFFSET feed sometimes show the same post twice?

  3. Why does a cursor usually include id as well as created_at?

0 of 3 answered.