Keyset / Cursor Pagination vs Slow OFFSET Pagination
Prefer keyset/cursor pagination over deep OFFSET for large tables.
In plain words
Instead of saying "skip the first 10,000 rows", say "give me the next 20 after the last one I saw".
Think of it like…
Reading a long book: OFFSET is counting pages from the start every time you sit down ("skip 400 pages…"); keyset is using a bookmark and opening right where you left off.
Where you’ve seen it
A feed API returns 20 posts per page, newest first. The response includes a cursor made from the last post's (created_at, id); the next request sends it back, and the query fetches posts strictly older than that pair using an index on (created_at, id).
Words you’ll hear
- OFFSET
- Number of rows to skip; the database still reads them.
- Keyset / seek method
- Filtering on the sort key's last seen value instead of skipping rows.
- Cursor
- An opaque token for the client that encodes the last row's sort key.
- Tiebreaker
- A unique column (id) added to the sort so the order is total and stable.
Visual diagram
Theory & example queries
Why OFFSET gets slow and inconsistent
To return rows 10,001 to 10,020, the database has to produce the first 10,020 rows in sorted order and discard 10,000 of them. Even with an index, the work grows with the offset, so deep pages and full exports crawl.
OFFSET also counts positions, not rows. If a new post is inserted at the top while a user is on page 3, everything shifts down by one, and page 4 starts with a post they've already seen. Deleting a row makes them skip one instead.
SELECT *FROM postsORDER BY created_at DESCLIMIT 20OFFSET 100000;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative deep page3 sample rows
| id | created_at | title |
|---|---|---|
| 8842 | 2026-08-18T09:12:00+00:00 | Indexing checklist |
| 8839 | 2026-08-18T09:11:00+00:00 | Release notes |
| 8831 | 2026-08-18T09:09:00+00:00 | Incident review |
Note: Only the first three representative rows of the 20-row page are shown. Exact work and values depend on the posts data; SELECT * would include every other column in the table.
reads about 100,020 rows to return 20.
Key takeaway: OFFSET's cost grows with page depth, and inserts shift the pages.
Writing keyset pagination
Sort by a unique, stable key, usually the sort column plus id as a tiebreaker, and create an index in that order. For the next page, filter for rows strictly after the last row of the previous page. PostgreSQL handles the row comparison (created_at, id) < ($1, $2) well with a matching index; on engines that optimise it poorly, expand it to created_at < $1 OR (created_at = $1 AND id < $2).
Return the last row's key to the client as an opaque cursor (for example base64-encoded), not as raw values they're tempted to edit. The trade-offs: there's no direct jump to page N, and a total count needs a separate (possibly approximate) query.
SELECT id, created_at, titleFROM postsWHERE (created_at, id) < ($1, $2)ORDER BY created_at DESC, id DESCLIMIT 20;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative next keyset page3 sample rows
| id | created_at | title |
|---|---|---|
| 899 | 2026-11-20T14:29:58+00:00 | Shipping update |
| 898 | 2026-11-20T14:28:40+00:00 | API design notes |
| 897 | 2026-11-20T14:28:40+00:00 | Pagination tips |
Note: Assumes the previous cursor was (2026-11-20T14:30:00+00:00, 900). The actual page and planner work depend on the cursor, data and index support.
with an index on (created_at DESC, id DESC).
Key takeaway: Unique sort key, matching index, filter strictly after the last seen row.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Make the sort order unique
Add a unique column (id) after the main sort column so no two rows tie and the order never changes between requests.
ORDER BY created_at DESC, id DESCWhen to use it & trade-offs
What it is
OFFSET pagination (ORDER BY id LIMIT 20 OFFSET 10000) makes the database read and throw away every row before the page, so deep pages get slower and slower. Keyset (cursor) pagination remembers the last row of the previous page and asks for rows after it (WHERE id > 10020 ORDER BY id LIMIT 20), so every page costs the same.
Why it matters: Infinite scroll, API list endpoints and data exports all page through large tables. With OFFSET, page 1 is fast but page 5,000 can take seconds, and rows inserted between requests cause duplicates or skipped items. It's a classic backend system-design and SQL interview topic.
When to reach for it
- Infinite-scroll feeds and timelines
- Public API list endpoints
- Batch jobs and exports that walk a whole table
When to avoid or be careful
- Deep OFFSET on large tables
- Keyset on a non-unique sort key without a tiebreaker
- Exposing raw cursor values that clients can tamper with
OFFSET vs keyset pagination
Strengths: Simple, supports page numbers.
Watch out: Slower the deeper you go; duplicates or skipped rows when data changes.
Strengths: Constant cost per page; stable under inserts.
Watch out: No random page access; needs a unique, indexed sort key.
Strengths: Fast pages and a rough total.
Watch out: The count isn't exact.
Interview signals & numbers to know
When this topic comes up
- “Page 5,000 of the API is slow”
- “Users see duplicate items when scrolling”
- Designing a paginated API
- Exporting a large table in chunks
- OFFSET performance
Benchmarks & rules of thumb
- OFFSET n
- reads n + LIMIT rows
- Keyset
- reads about LIMIT rows per page
- 2
- columns in a typical cursor: sort value + id
Common mistakes & follow-ups
Common interview mistakes
- Sorting only by created_at, so rows with the same timestamp are skipped or repeated between pages.
- Creating the index in a different column order or direction than the ORDER BY.
- Using
>=instead of>(or<=instead of<) and repeating the last row of the previous page.
Likely interviewer follow-ups
- Why does OFFSET pagination get slower on later pages?
- How do you handle ties in the sort column with keyset pagination?
- How would you support "previous page" with cursors?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Keyset / Cursor Pagination vs Slow OFFSET Pagination with hands-on SQL practice and interview Q&A.