Topic B3
Pagination: offset vs cursor
Why deep pages get slower with OFFSET, and why cursors don't.
Watch: the first way reads and throws away every row before the page you asked for. The second jumps straight there.
- finished / the result
- no longer used
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
| OFFSET | Cursor | |
|---|---|---|
| Jump to page 37 | Yes | No |
| Deep pages | Slow | Just as fast |
| Data changing while paging | Rows repeat or vanish | Safe |
| Good for | small admin tables | feeds, infinite scroll, public APIs, exports |
Quiz
LIMIT 20 OFFSET 100000. Roughly how many rows does the database read?
Why does an OFFSET feed sometimes show the same post twice?
Why does a cursor usually include id as well as created_at?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.