SQL · Queries that survive scale
How do you implement pagination efficiently?
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.
SELECT id, created_at, title
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 4000;SELECT id, created_at, title
FROM posts
WHERE (created_at, id) < ('2026-09-01', 98123)
ORDER BY created_at DESC, id DESC
LIMIT 20;- 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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does OFFSET become slow at high values?
- 2How do you handle page numbers with keyset pagination?
- 3What index supports keyset pagination?
- 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.