TECHNOLOGY

PostgreSQL keyset pagination needs the full ordering tuple

In this article
THE QUICK TAKE

For non-null ascending keys, align the row predicate, ORDER BY and cursor tuple, including a unique tie-breaker rather than only the visible timestamp.

Give equal-time records a definite order

A document API lists analyses by creation time, and several records share that timestamp. PostgreSQL’s LIMIT guidance requires an order that uniquely constrains the selected rows. Ordering only by creation time leaves ties unresolved. Add a suitable unique identifier to the ordering, and include it in the continuation boundary so each analysis has an unambiguous position relative to the last returned record.

Carry the full non-null tuple forward

For ascending non-null creation time and identifier, a keyset boundary can compare (created_at, id) with the last returned pair. The row-comparison reference defines comparison from left to right. A predicate using only creation time can skip remaining records at the same timestamp. Using equality on time without the identifier’s direction can instead repeat records or select an inconsistent subset of that tied group.

Match predicate direction to the requested ordering

The tuple example assumes both fields ascend. Mixed ascending and descending fields need a predicate that actually matches their ordering; a single row comparison should not be copied mechanically. Index ordering guidance likewise distinguishes multicolumn direction combinations. Define null behavior separately when nullable keys are allowed. The continuation contract includes the whole ordering, not merely a cursor value whose contents happen to resemble a timestamp.

Use an index as access support rather than hidden semantics

A matching ordered index can help fetch a limited next page efficiently, but the query still needs an explicit ORDER BY. Internal index tie-breaking is not a substitute for the API’s declared unique ordering. Progressive reading helps follow the endpoint into its actual SQL and index definition. Review the predicate and ordering together before attributing omitted records to a client pagination bug.

Distinguish continuation from a frozen dataset

Keyset selection defines where another query begins; it does not by itself promise an unchanged collection while records are inserted or ordering fields change. Define the necessary consistency separately. Tool observations should preserve the last full tuple and query settings. A useful review demonstrates how equal-time records remain traversable without presenting successful keyset pagination as a general snapshot guarantee or treating the visible creation timestamp as a complete record identity.

Earn rental income from GPUs

Have idle GPUs or looking to fund AI infrastructure? Retrivium finds a rental platform, sets up the server and helps you assess income and costs with a pilot.

Explore GPU hosting
← All articles