Cursor Pagination for Stable Pages

Paginate a query by comparing against the last seen key instead of a numeric offset, so pages stay stable when rows are inserted.

PythonData Fetching

Code

pythonsnippet
22 lines
import sqlite3
from typing import List, Optional, Tuple


def page_by_cursor(
    connection: sqlite3.Connection,
    after_id: Optional[int],
    limit: int,
) -> Tuple[List[Tuple[int, str]], Optional[int]]:
    if limit <= 0 or limit > 100:
        raise ValueError("limit must be between 1 and 100")
    if after_id is None:
        rows = connection.execute(
            "SELECT id, name FROM items ORDER BY id ASC LIMIT ?", (limit,)
        ).fetchall()
    else:
        rows = connection.execute(
            "SELECT id, name FROM items WHERE id > ? ORDER BY id ASC LIMIT ?",
            (after_id, limit),
        ).fetchall()
    next_cursor = rows[-1][0] if len(rows) == limit else None
    return rows, next_cursor

How it works

Count the function page_by_cursor as the entire surface area of Cursor Pagination for Stable Pages.

Reach for sqlite3 and what you get is List, Optional, Tuple — that is the whole API contact area. The failure path is explicit — ValueError is raised when the guard condition holds.

What to watch for

  • Plan for an install step: sqlite3 is a real dependency, resolved by the package manager.
  • The guard limit <= 0 or limit > 100 short-circuits the flow with an early raise when its condition holds.

Using it

Entry signature: def page_by_cursor( connection: sqlite3.Connection, after_id: Optional[int], limit: int, ) -> Tuple[List[Tu…

page_by_cursor is what another module would consume; nothing else here is load-bearing for callers.

Key statements

if after_id is None:
    rows = connection.execute(
        "SELECT id, name FROM items ORDER BY id ASC LIMIT ?", (limit,)
    ).fetchall()
def page_by_cursor(
connection: sqlite3.Connection,
after_id: Optional[int],
limit: int,
) -> Tuple[List[Tuple[int, str]], Optional[int]]:

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
It throws `ValueError` before any real work runs, via the guard `limit <= 0 or limit > 100` — handle it at the call site or let it propagate deliberately.
Are there third-party dependencies?
`sqlite3` — install it with the package manager before running.