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
Dialect · Portable SQLRuntime · SQLite sample DB
The core keyset predicate is portable; this playground uses SQLite LIMIT syntax for the bounded page.
SQL
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.