Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 136/ 160
07. Indexing, Query Optimization & Performance Tuning

Keyset / Cursor Pagination vs Slow OFFSET Pagination

Prefer keyset/cursor pagination over deep OFFSET for large tables.

IntermediateKeyset · Cursor3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The slow versionQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  posts5ORDER BY6  created_at DESC7LIMIT8  209OFFSET10  100000;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative deep page3 sample rows
Representative deep page
idcreated_attitle
88422026-08-18T09:12:00+00:00Indexing checklist
88392026-08-18T09:11:00+00:00Release notes
88312026-08-18T09:09:00+00:00Incident 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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Next page, newest firstQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  created_at,4  title5FROM6  posts7WHERE8  (created_at, id) < ($1, $2)9ORDER BY10  created_at DESC,11  id DESC12LIMIT13  20;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative next keyset page3 sample rows
Representative next keyset page
idcreated_attitle
8992026-11-20T14:29:58+00:00Shipping update
8982026-11-20T14:28:40+00:00API design notes
8972026-11-20T14:28:40+00:00Pagination 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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

with an index on (created_at DESC, id DESC).

Key takeaway: Unique sort key, matching index, filter strictly after the last seen row.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

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.

SQL at this step
1ORDER BY2  created_at DESC,3  id DESC
What to watch at this step
Tiebreaker
required
Tip: use ← → to move between steps

When 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

LIMIT / OFFSET
Best for: Small tables, admin screens, "jump to page N" UIs

Strengths: Simple, supports page numbers.

Watch out: Slower the deeper you go; duplicates or skipped rows when data changes.

Keyset / cursor
Best for: Infinite scroll, APIs, exports over large tables

Strengths: Constant cost per page; stable under inserts.

Watch out: No random page access; needs a unique, indexed sort key.

Keyset + approximate count
Best for: UIs that want "about 1.2M results" with fast paging

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?
Interview tip: Explain both problems with OFFSET (cost grows with depth, and inserts shift the pages), then write the keyset query with a tiebreaker and a matching index. Mentioning opaque cursors shows API-design experience.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Optimizing Slow GROUP BY, DISTINCT & ORDER BY Operations
Next topic
Table Partitioning (Range, List, Hash) & Partition Pruning