SQL · Queries that survive scale

How do you implement pagination efficiently?

Mediumpaginationlimit offsetkeysetUpdated Oct 2026
Quiz this track

Short answer

OFFSET pagination is simple but scans and discards skipped rows. Keyset pagination uses the last seen key in a WHERE condition, stays fast at depth, and requires a stable unique sort order.

Offset pagination is convenient for page numbers but becomes slower as the offset grows, because the database still processes the skipped rows. Keyset pagination remembers where the previous page ended and seeks directly to the next position.

sql
SELECT id, created_at, title
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 4000;
The offset version reads and discards 4000 rows before returning 20.
sql
SELECT id, created_at, title
FROM posts
WHERE (created_at, id) < ('2026-09-01', 98123)
ORDER BY created_at DESC, id DESC
LIMIT 20;
Keyset pagination seeks from the last row of the previous page. Tuple comparison syntax varies by engine.
  • Always order by a unique combination, usually the sort column plus a tie-breaker such as id
  • An index on (created_at DESC, id DESC) supports the keyset query
  • Keyset pagination cannot jump directly to page 200, so it fits infinite scroll better than page numbers
  • Offset pagination can show duplicate or missing rows if data changes between requests
  • For small tables or admin tools, OFFSET is often acceptable

If the UI needs page numbers and deep offsets, consider restricting how deep users can go or maintaining a separate ordered index or snapshot. Do not assume LIMIT makes an OFFSET query cheap.

A common production bug is paginating without a deterministic tie-breaker. When many rows share the same timestamp, the page boundary can repeat or skip rows.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why does OFFSET become slow at high values?
  2. 2How do you handle page numbers with keyset pagination?
  3. 3What index supports keyset pagination?
  4. 4Why is a tie-breaker required?

Say it in the interview

OFFSET pagination is easy but it still processes the rows it skips, so deep pages get slower. Keyset pagination uses the last row's sort key in the WHERE clause and seeks directly to the next page, which stays fast. I always add a unique tie-breaker to the sort order and create an index that matches it. The trade-off is that keyset pagination does not support arbitrary page jumps.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.