smartyfy.mrindigi.com

Databases & SQL Master Course — 147. Pagination and Stable Cursors

Lesson 147 Pagination and Stable Cursors

Prerequisites and objectives

Complete ordered queries, composite indexes, and application boundaries. You will build a stable descending order with a unique tie-breaker, compare offset and keyset pagination under inserts and deletes, and explain why a cursor does not automatically create a frozen snapshot across requests.

A page boundary needs a total order

Sorting only by creation time is ambiguous when several events share the same timestamp. Add a unique identity as a tie-breaker so every row has one defined position. This fixture uses canonical non-NULL UTC text timestamps of identical format and descending order on both timestamp and identity.

Offset pagination asks the database to skip a number of rows in the current ordered result. Keyset pagination asks for rows after the last seen key in that order. For a descending timestamp and identity order, the next page contains an earlier timestamp, or the same timestamp with a smaller identity.

Both approaches still need the same authorization scope and filters on every page. A cursor should represent values and a documented sort version, not a caller-supplied SQL condition. Validate its shape and bind its values through the driver. If tamper resistance is part of the API contract, protect the cursor accordingly; an opaque encoding alone is not authorization.

CREATE TABLE lab_event147(id INTEGER PRIMARY KEY,created_at TEXT NOT NULL,title TEXT NOT NULL);
INSERT INTO lab_event147 VALUES(1,'2026-10-10T00:00:00Z','One'),(2,'2026-10-11T00:00:00Z','Two'),(3,'2026-10-11T00:00:00Z','Three'),(4,'2026-10-12T00:00:00Z','Four');
CREATE INDEX lab_event147_order ON lab_event147(created_at DESC,id DESC);
Initial deterministic descending order
Position Event identity UTC timestamp
1 4 2026-10-12T00:00:00Z
2 3 2026-10-11T00:00:00Z
3 2 2026-10-11T00:00:00Z
4 1 2026-10-10T00:00:00Z

Worked practice

Exercise 1

Fetch the first page and continue after its complete final key.

Worked solution
-- Connection A
SELECT id,created_at FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2;
-- Connection A
-- Bind values through the client API: ["2026-10-11T00:00:00Z", "2026-10-11T00:00:00Z", 3]
SELECT id FROM lab_event147 WHERE created_at<? OR (created_at=? AND id<?) ORDER BY created_at DESC,id DESC LIMIT 2;

The first page ends at timestamp October eleven, identity three. The equality branch admits identity two at that same timestamp. Using only an earlier-timestamp predicate would skip it. The ordering and the boundary predicate must describe the same lexicographic order.

Exercise 2

Insert a newer row between pages and compare the two continuation methods.

Worked solution
-- Connection A
SELECT id,created_at FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2;
-- Connection B
INSERT INTO lab_event147 VALUES(5,'2026-10-13T00:00:00Z','Five');
-- Connection A
SELECT id FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2 OFFSET 2;
-- Connection A
-- Bind values through the client API: ["2026-10-11T00:00:00Z", "2026-10-11T00:00:00Z", 3]
SELECT id FROM lab_event147 WHERE created_at<? OR (created_at=? AND id<?) ORDER BY created_at DESC,id DESC LIMIT 2;

The new leading row shifts positional offsets. OFFSET two now returns identity three again, duplicating a row from the first page. The keyset predicate remains anchored after the saved key and returns two then one. It intentionally does not include the newly inserted row that sorts before the boundary.

Exercise 3

Delete a previously displayed leading row before fetching the next page.

Worked solution
-- Connection A
SELECT id,created_at FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2;
-- Connection B
DELETE FROM lab_event147 WHERE id=4;
-- Connection A
SELECT id FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2 OFFSET 2;
-- Connection A
-- Bind values through the client API: ["2026-10-11T00:00:00Z", "2026-10-11T00:00:00Z", 3]
SELECT id FROM lab_event147 WHERE created_at<? OR (created_at=? AND id<?) ORDER BY created_at DESC,id DESC LIMIT 2;

Removing identity four shifts the remaining rows toward the front. The offset continuation skips identity two, while the keyset continuation still returns it. These changes are performed only in the fresh fictional fixture and are discarded when the scenario ends.

Exercise 4

Change an unseen row’s sort key after the first page and inspect the limitation.

Worked solution
-- Connection A
SELECT id,created_at FROM lab_event147 ORDER BY created_at DESC,id DESC LIMIT 2;
-- Connection B
UPDATE lab_event147 SET created_at='2026-10-14T00:00:00Z' WHERE id=2;
-- Connection A
-- Bind values through the client API: ["2026-10-11T00:00:00Z", "2026-10-11T00:00:00Z", 3]
SELECT id FROM lab_event147 WHERE created_at<? OR (created_at=? AND id<?) ORDER BY created_at DESC,id DESC LIMIT 2;

Identity two moves ahead of the stored cursor and no longer satisfies the next-page predicate. Keyset pagination avoids positional drift but cannot promise a historical complete snapshot when sort keys or membership change across independent requests. Prefer immutable ordering keys where the product permits, or design a separate snapshot/export mechanism for point-in-time completeness.

Make the cursor contract explicit

Store every component needed to resume the order. Include the filter or query version when a cursor should not be reused with a different search. Recompute authorization from the current request; do not trust a tenant identity merely because it appears inside a cursor. A user who loses access between pages should not retain access through an old token.

Mixed ascending and descending keys require a boundary expression that follows each component’s direction. Nullable keys need an explicit NULL placement and continuation policy. This lesson avoids those complications with non-NULL values and matching descending directions, rather than pretending one comparison works for every sort.

A supporting composite index can make keyset continuation efficient, but inspect the actual query plan and measure realistic pages. Offset can still be convenient for small stable results or direct numbered-page navigation. Keyset cursors naturally support next-page traversal and do not cheaply provide an arbitrary page number without additional work.

Distinguish browsing from a consistent export

A user browsing a changing feed may accept that new items appear only after refreshing from the beginning. A reconciliation export may require one consistent dataset with no omissions. That stronger requirement may need a database snapshot, a materialized export, or another bounded process rather than a long-lived interactive connection held open for a human.

Do not advertise a cursor as a snapshot unless the system actually retains and enforces the relevant historical view. The SQLite trials deliberately use separate autocommit statements between pages so their changing-data behavior is visible.

Pitfalls and summary

Always define a deterministic total order, carry the complete last key, and keep the continuation predicate aligned with the sort direction. Test ties, insertions, deletions, and mutable keys. Keyset pagination solves position-based drift under its assumptions, while consistency, authorization, and completeness remain explicit application requirements.

Knowledge check

Question 1

Why is id included after created_at in this order?

  1. To place equal timestamps in a deterministic unique order
  2. To make timestamps immutable automatically
  3. To authorize access to every event
  4. To allow timestamp-only cursors to skip the identity component
Answer and explanation

A. A unique tie-breaker defines an unambiguous page boundary.

Question 2

Which condition admits the remaining event tied at the cursor timestamp?

  1. The timestamp is earlier, with no equality branch
  2. The id is greater than the cursor id for every timestamp
  3. The timestamp equals the cursor timestamp regardless of id
  4. The timestamp equals the cursor timestamp and id is smaller than the cursor id
Answer and explanation

D. The equality branch follows the descending identity tie-breaker.

Question 3

Why did an insertion before the boundary duplicate identity three under OFFSET?

  1. OFFSET counts previously returned identities rather than current row positions
  2. The saved offset is interpreted as an event identity rather than a row count
  3. The current row positions shifted while the numeric offset stayed two
  4. LIMIT automatically preserves the earlier page’s timestamp boundary
Answer and explanation

C. Offsets refer to positions in the current result, not remembered identities.

Question 4

What limitation did the changed timestamp demonstrate?

  1. An unseen row can move before the cursor and be omitted from later pages
  2. Keyset pagination always preserves a historical snapshot
  3. The cursor prevents all updates to ordered columns
  4. A composite index freezes every result row
Answer and explanation

A. Stable boundary values do not freeze changing row membership or sort keys.

Question 5

Which requirement needs more than an ordinary stateless browsing cursor?

  1. A deterministic tie-breaker in one query
  2. A complete point-in-time export despite concurrent changes
  3. A bounded page size
  4. A fixed approved descending sort
Answer and explanation

B. Snapshot completeness requires a mechanism that actually preserves the intended dataset.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references