Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

Write a stable next-page SQL query without relying on a large OFFSET.

Answer

Use keyset pagination: order by a stable unique tuple and request rows after the last tuple returned by the previous page. This avoids scanning an ever-growing offset and prevents many duplicate or skipped rows when new records are inserted between page requests. The ordering must be deterministic, usually timestamp plus primary key.

Strong answer includes

  • uses the last seen ordering key instead of OFFSET
  • uses a unique deterministic ordering tuple
  • explains stability and performance benefits under changing data

Practical example

Solution · Stable next-page query
Dialect · Portable SQLRuntime · SQLite sample DB

The core keyset predicate is portable; this playground uses SQLite LIMIT syntax for the bounded page.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

Use the last seen (created_at, id) tuple as the cursor and keep the predicate aligned with the deterministic descending ORDER BY. The playground uses SQLite LIMIT syntax and sample parameter values.

Expected result: The next bounded page after the configured sample cursor, in deterministic descending order.

#sql#pagination#performance#ordering

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery