Relational databases: collection tree

Relational databases

Pagination and consistent exports

Deep diveAbout 14 minutes AI-generated

A page of results needs a rule for where the next page starts. An export needs a rule for which version of the data it contains. Those are different decisions. Remembering the last order on a page can make a changing list pleasant to browse without making a download a consistent account of the shop.

Suppose the shop’s order screen shows the newest orders first, two at a time. While someone reads the first page, another order arrives. “Skip the first two rows” now skips a different pair. A keyset cursor remembers the last ordering key instead: “continue after this time and order ID”. It avoids that shift, but an order whose time changes can still cross the boundary, and its other values can change between reads.

Every example starts from the same shop. For this order-list exercise, add orders 201 and 202. Both are for customer 3. Both were placed at the same instant as order 103, 10:15 UTC on 20 October 2026. The list has one row per order; it uses no order-line or payment details for the two additions. The SQL uses PostgreSQL 18. The examples concern ordered results and changes between reads, rather than the engine’s execution plan.

LIMIT and OFFSET

LIMIT caps the number of result rows returned. OFFSET skips a number of result rows first. With a page size of two, the first page has offset zero, the second offset two, the third offset four.

SELECT order_id, placed_at, status
FROM orders
ORDER BY placed_at DESC, order_id DESC
LIMIT 2;

DESC puts the largest value first. The timestamp orders the rows from newest to oldest; the ID orders rows whose times tie. Our five orders therefore appear in the order 202, 201, 103, 102, 101. The first page returns 202 and 201.

The ID matters before we think about changes. An order by timestamp alone would leave 202, 201 and 103 tied, with no promised order among them. To divide a result predictably, the ordering terms together must distinguish every result row. A unique order ID supplies that distinction here.

SELECT order_id, placed_at, status
FROM orders
ORDER BY placed_at DESC, order_id DESC
LIMIT 2 OFFSET 2;

With no changes, the second query skips 202 and 201, then returns 103 and 102. Now suppose order 203 arrives at 09:00 UTC on 21 October, before the second request. The new first two rows are 203 and 202, so the same offset returns 201 and 103. In a separate change, delete already-read 202 instead. The second query then skips 201 and 103, returning 102 and 101.

The numbered boundary moves
Figure 1. These are results from successive queries, not the engine’s physical execution.
Figure as text

Insert 203 before the boundary: The next query skips 203 and 202, then returns 201 and 103. Order 201 appears on both pages. Delete already-read 202: The next query skips 201 and 103, then returns 102 and 101. Order 103 is missed: it moved into the skipped positions.

The insertion made 201 appear twice. The deletion made 103 disappear from the traversal. Both queries used a unique order and answered correctly at the time they ran. The problem is that a row count describes a position in the current result, and that position changes when earlier rows arrive or leave.

Numbered pages are useful when people need to jump to a page, especially over a small or fixed result. They also have a cost: the rows an offset skips still have to be computed inside PostgreSQL. Returning ten rows after skipping a million does not make the skipped million free. Whether an index or a sort supplies that order changes the work, but not the offset’s meaning.

Keyset pagination

Keyset pagination continues from a value in the order instead of counting from the start. The first page still uses the first query above. Its last returned row is 201, so save that row’s complete ordering key: its timestamp and ID.

In a descending order, the next rows have a smaller timestamp, or the same timestamp and a smaller ID. Order 103 has the same timestamp as 201 but a smaller ID, so it must pass the second part of that test.

Figure 2Continue inside the timestamp tie

Page 1 ended at (20 Oct 10:15 UTC, 201).

Time alone · placed_at < cursor time

20220 Oct · 10:15Equal time → excluded
20120 Oct · 10:15Equal time → excluded
10320 Oct · 10:15Equal time → excluded

Next page: 102, 101

Whole key · (placed_at, order_id) < cursor

20220 Oct · 10:15ID is greater → before the boundary
20120 Oct · 10:15The boundary itself → excluded

↓ continue after 201

10320 Oct · 10:15ID is smaller → keep this row

Next page: 103, 102

Descending time and descending ID. The time-only test loses 103. Comparing the pair keeps it; the strict comparison excludes the boundary row 201.

The complete next-page condition is:

SELECT order_id, placed_at, status
FROM orders
WHERE placed_at < timestamptz '2026-10-20 10:15:00+00'
   OR (placed_at = timestamptz '2026-10-20 10:15:00+00'
       AND order_id < 201)
ORDER BY placed_at DESC, order_id DESC
LIMIT 2;

PostgreSQL can write the same test as a row comparison. It compares the first pair of values, then moves to the next pair only when they are equal:

SELECT order_id, placed_at, status
FROM orders
WHERE (placed_at, order_id)
    < (timestamptz '2026-10-20 10:15:00+00', 201)
ORDER BY placed_at DESC, order_id DESC
LIMIT 2;

The answer is 103 and 102. Use a strict <: <= would include 201 itself again. Saving just the timestamp and testing placed_at < ... would lose 103. Testing placed_at <= ... would include the already-read timestamp group again. The pair identifies a boundary inside that group.

This condition also gives the database a range it can find in a suitable index, rather than an instruction to discard all earlier result rows. An index matching the filters and order can make that cheap. The predicate alone does not guarantee a particular plan or constant work: rejected rows, joins and sorting still matter. Index design and measured access costs belong to Indexes and access paths.

Matching the whole sort order

The row-comparison shorthand works here because both terms are non-null and both sort in the same direction. Derive the continuation from the order you actually use. For example, change the ID to ascending within each timestamp:

SELECT order_id, placed_at, status
FROM orders
WHERE placed_at < timestamptz '2026-10-20 10:15:00+00'
   OR (placed_at = timestamptz '2026-10-20 10:15:00+00'
       AND order_id > 201)
ORDER BY placed_at DESC, order_id ASC
LIMIT 2;

That order starts 103, 201, 202, 102, 101. After 201, it needs 202 and 102. Time still moves downwards, but ID moves upwards inside a tie, so its comparison becomes >. A plain (placed_at, order_id) < (...) would express the wrong order.

Nulls need an explicit place too. Take the shop’s separate package-weight example: P3 weighs 65 grams, P9 weighs 820 grams, and P7 has not been measured. With ORDER BY package_weight_g ASC NULLS LAST, product_id ASC, the order is P3, P9, P7. After P9, a numerical comparison alone would discard P7: comparing its null weight with 820 is unknown, not true. Include the null group deliberately:

SELECT product_id, package_weight_g
FROM products
WHERE package_weight_g > 820
   OR (package_weight_g = 820 AND product_id > 'P9')
   OR package_weight_g IS NULL
ORDER BY package_weight_g ASC NULLS LAST, product_id ASC
LIMIT 2;

Once the cursor is inside that last, null group, continue with package_weight_g IS NULL AND product_id > .... There are no measured weights after it. The cursor must distinguish a null boundary from a measured one; changing NULLS LAST to NULLS FIRST changes these cases. For text terms, preserve the same collation, the rules used to order strings, on every page too.

Finally, use the identity of a result row. If a join produces one row per order line, an order ID cannot break ties between lines of the same order. A descending order by placed_at, order_id, line_no needs all three boundary values and matching directions. Joins and the meaning of a result row establishes why those repeated order IDs are separate rows worth preserving.

Previous pages and the end of the list

To fetch the preceding page, start from the first row on the current page. Page two begins at 103. Ask for keys greater than its key, reverse the query order, then reverse the returned rows for display:

SELECT order_id, placed_at, status
FROM orders
WHERE (placed_at, order_id)
    > (timestamptz '2026-10-20 10:15:00+00', 103)
ORDER BY placed_at ASC, order_id ASC
LIMIT 2;

The query returns 201, 202: the nearest preceding rows first. Display them as 202, 201 to restore the screen’s newest-first order. Keeping the descending query order would fetch the start of the list, which need not be the page immediately before this one. With changing data, even a correctly fetched previous page need not reproduce the page someone saw earlier.

To show whether another page is available, request one extra row. With page size two, use LIMIT 3, return only the first two, and make the next cursor from the second row, not the extra one. On the first read the extra row is 103: it proves a next row existed in that read. It does not count the remaining rows, nor promise they will still be present when the next request arrives.

What a cursor must preserve

An API usually wraps the boundary in a page token, a string the client returns unchanged on its next request. Inside it, or in server-side state it refers to, the service needs enough information to reconstruct the same continuation.

Continuing the same order-list query
PreserveWhy it matters
Last returned timestamp and IDLocate the boundary inside timestamp ties.
Filters, including the list’s scopeA cursor from all orders is not a cursor from just pending orders or one customer’s orders.
Sort definition and versionDirections, null placement and text comparison rules determine what “after” means.
Expiry and any retained-result identitySay when the continuation can no longer be honoured, and which saved export it belongs to.

Use database precision for boundary values. PostgreSQL timestamps can distinguish microseconds. Rounding a returned timestamp to milliseconds before putting it in a token moves the boundary; reading an ID through a number type that cannot represent it exactly has the same problem. Preserve the exact typed value and bind it back as a query parameter. Display formatting is a separate choice.

Changing a filter or sort starts a new traversal. Either bind those choices into the token or check the new request against the saved query definition; reject a mismatch with an instruction to restart. An expired token also needs an explicit restart outcome. Quietly treating it as a first-page request makes a continuation repeat the start.

The token is continuation data, not permission to read the rows. Check the caller’s current authority on every request, and protect token integrity if clients must not alter its scope or boundary. Encoding readable fields in base64 supplies no such protection. These are API design choices; Google’s pagination guidance makes the distinction between a page token and authorisation explicit.

An API cursor need not keep a database connection open. A database cursor is different: it is database-side state that lets one session fetch a query’s result in batches. The same word describes two mechanisms with very different lifetimes.

Changes between pages

A saved key does not depend on how many rows precede it. Delete 202 and the next request still asks for keys after 201. Insert 203 before the key and the next request still begins with 103. Changing a row’s ordering value is different: it moves the row relative to the saved boundary.

The key stays fixed; rows can move
Figure 3. These are results from successive queries, not the engine’s physical execution.
Figure as text

Delete already-read 202: 202 has gone, but the saved key has not moved. Continue after 201: return 103 and 102. Insert 203 before the boundary: 203 is before the saved key. Continue after 201: return 103 and 102. The new order belongs to a refresh of the start. Move unread 103 before the boundary: 103 is now before the saved key, so it fails the continuation test. Return 102 and 101. The traversal never shows 103. Move already-read 202 after the boundary: 202 is now after the saved key. Return 103 and 202. The traversal shows 202 again, under its changed ordering key.

When unread 103 moves before the key, the next query cannot see it. When already-read 202 moves after the key, it can appear again. The cursor identifies an ordering position; it does not remember every identity already shown. Choosing stable ordering fields removes these particular movements, but it does not freeze the rest of the query.

Filters can change too. On a pending-only list, an unread order marked paid disappears from later pages. An order that becomes pending can join the unread part, or be missed if its key lies in the part already passed. A customer list based on a changing name or a ranking based on a changing score has the same issue in its sort terms. Decide whether the interface is browsing the current list or promising the membership from an earlier read.

A high-water key adds an upper bound captured at the start. In this descending list that ceiling is the first key, belonging to 202. Requiring keys at or below it excludes later arrivals with greater keys, so the run cannot grow at that end.

It does not create a snapshot, though. A later transaction may commit a row with a key below the ceiling after the traversal has already passed its position. The ceiling neither makes that row visible earlier nor brings the traversal back to find it. Updates, deletions and changing values remain possible too.

For ordinary browsing, that can be the right contract: continue through the current list, with a refresh to see new entries at the start. It is not enough for an export that must contain the rows and values visible at one database snapshot.

One snapshot for an export

A consistent export needs to say what it preserves: all result rows and their selected values from one database snapshot. That includes the values used by joins and calculations, not just the order IDs. Reading a large result in batches changes how it is delivered; it must not silently change which database state supplies those batches.

At PostgreSQL’s default isolation level, Read Committed, each ordinary SELECT takes a fresh snapshot. Putting several such queries between BEGIN and COMMIT does not make them share one. In a read-only Repeatable Read transaction, they use the snapshot established by the first query. The read-only mode keeps this export from making application writes; the isolation level is what keeps its reads on that snapshot.

Suppose the first batch is read while 103 is pending, then another transaction marks it paid and commits before the next batch. Separate Read Committed queries can copy its newer paid status. In one Repeatable Read transaction whose snapshot was established by the first query, the later batch still copies pending. The export’s promise determines which result is acceptable.

Which version enters the export?
Figure 4. A keyset boundary protects position, not the values in an earlier snapshot.
Figure as text

The first batch copies pending orders 202 and 201. Another transaction commits order 103 as paid. The next batch reads 103 and 102. With fresh Read Committed snapshots 103 is copied as paid; with the first Repeatable Read snapshot it remains pending in the export. Both finish with order 101 paid.

For the separate-query approach, start the transaction before the first batch and keep all batches on that same transaction and connection:

BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;

SELECT order_id, placed_at, status
FROM orders
ORDER BY placed_at DESC, order_id DESC
LIMIT 2;

SELECT order_id, placed_at, status
FROM orders
WHERE (placed_at, order_id)
    < (timestamptz '2026-10-20 10:15:00+00', 201)
ORDER BY placed_at DESC, order_id DESC
LIMIT 2;

-- Continue from the last returned key until exhausted.
-- End the transaction only after the final batch.
COMMIT;

Within that snapshot, the membership and stored values stay fixed, so the unique order divides one result into batches without the shifts above. This example selects stored columns only. A snapshot of table data does not freeze an external service or turn a volatile expression such as a fresh random value into a stored fact; fix such inputs if they belong in the export’s definition.

Another route is to execute one query and consume its result in batches through a driver or database cursor. That avoids issuing a new list query for every batch. It still needs a bounded lifetime and a connection owner. PostgreSQL’s ordinary SQL cursor lives inside its transaction; a cursor declared WITH HOLD can survive commit by retaining its result, but remains tied to that database session. It is not a durable export job or an API page token. Driver streaming and cancellation mechanics belong to SQL at the application boundary.

Resuming the same export

Saving the last key lets a new query continue from a position. It cannot restore a snapshot whose transaction has ended. Rerunning after 201 in a new transaction can read 103 as paid, even if the original export needed its earlier pending status.

Saving only the membership IDs is not enough either. They identify the same orders, but joining those IDs back to the live table reads their current values. If an order has been deleted, even that row may be missing. To resume the same exported content later, retain the required projection: the columns and calculated values the export actually delivers, with an order or ordinal for reading them back.

Capture while 103 is pending; read after it becomes paid
What is savedLater read of 103Preserves the original content?
Its ordering keyA new query can return paid.No: it preserves a position.
Its ID, joined to live ordersPaidNo: it preserves membership only.
ID, time and status copied from the export snapshotPendingYes, for these selected columns.

A background job can copy the required result into a retained table or output file, then close the source transaction. Later download requests read that retained result. If several source queries build it, they must share the chosen snapshot too. Store all values the download needs, rather than looking some of them up again later.

Give that retained result an identity and a completion state. A resume token can refer to the result and the next row or byte position, with an expiry matching its retention. After expiry, offer a deliberately new export; do not call it a continuation of the old content. How a worker records progress and recovers a failed job is a separate protocol from choosing what this result means.

The cost of keeping a result available

Keeping the transaction open preserves its snapshot, but ties up a connection. In PostgreSQL it can also prevent vacuum from reclaiming old row versions that the snapshot might need. The cost depends on changes made while it is open, not merely on how many rows the export returns. A read-only export can therefore affect a busy database even while it waits for a slow client.

Materialising the output spends storage and write work instead. The source transaction can end once the copy is complete, and a person can download later without holding that snapshot open. The retained data still needs space, access checks and eventual removal.

Choose the promise before choosing the delivery mechanism
NeedA suitable approachBound its cost
Browse a changing listShort-lived keyset page token; fresh read per request.Page size, query duration and token lifetime.
Read one snapshot promptlyOne result in batches, or batch queries in one read-only snapshot transaction.Transaction duration and client waiting.
Download the same content laterRetained projection or completed output file.Generation time, output size and retention.

Cancellation must reach the work that is consuming those resources. Stopping an HTTP response alone need not stop a database query or end its transaction. The application must cancel or finish the active operation, close its cursor where applicable, and end or roll back the transaction before releasing the connection. Bound waiting between batches as well as time spent executing queries.

A partial file needs to remain recognisable as partial. Mark a retained export complete only after all required rows and final output have been written successfully. If generation fails, a client must not mistake the bytes already received for a complete result. Retaining a finished export separates that generation outcome from a download that can be retried later.

Use the list’s continuation contract for navigation and the export’s snapshot contract for reproducibility. A complete ordering key tells the next request where to continue. Keeping the chosen snapshot, or retaining the content read from it, tells the eventual reader what the result contains.

Trying the queries

Download the data and pagination queries to reproduce the list results in a PostgreSQL session. The script creates temporary projected tables, keeps each change independent and rolls everything back. It includes the time-only and non-strict counterexamples, mixed directions, previous-page query and null-weight cases.

The list SQL was checked in PGlite 0.5.8, a WebAssembly build of PostgreSQL 18.3. The two-session snapshot comparison and retained-value comparison were checked separately on a disposable PostgreSQL 18.6 server. These checks establish result meaning, not performance.

Sources and further reading

Checked against primary documentation on 25 October 2026. Pagination examples use ordinary reads of stored values, with the explicitly stated ordering and independent changes.