How would you implement pagination in SQL queries?

Instruction: Describe the approach and SQL syntax you would use to achieve pagination in a dataset.

Context: This question assesses the candidate's ability to manipulate large datasets efficiently, ensuring they can manage data retrievals effectively in pages.

Updated

Official answer

Pagination requires a deterministic total order. In PostgreSQL, ORDER BY created_at, order_id LIMIT 20 OFFSET 40 requests the third page if IDs break timestamp ties. Large offsets can require substantial skipped work, and concurrent inserts/deletes can shift later pages.

For ascending keyset pagination, assume non-NULL created_at and a unique order_id. After a cursor at timestamp 2026-01-01 12:00UTC and ID 100:

SELECT order_id, created_at
FROM orders
WHERE (created_at, order_id) > (TIMESTAMPTZ '2026-01-01 12:00:00+00', 100)
ORDER BY created_at, order_id
LIMIT 20;

The cursor includes both fields so timestamp ties are not skipped. A suitable composite index is a candidate to measure, not a universal speed guarantee. Bind cursor values and validate them; specify separate rules for NULLs or descending order.

Keyset pagination does not automatically provide a frozen snapshot. Changes to sort keys or eligibility can still alter traversal. Use immutable ordering or a defined snapshot strategy when consistent export semantics are required; arbitrary page-number jumps are less convenient with cursors.

Related Questions