A feed loads six posts in groups of two. Three posts have the same timestamp, and the second page ends right in the middle of that group. If the next request asks only for older timestamps, it skips a post. Keyset pagination solves that boundary by sending both the timestamp and the unique ID of the last post shown. This SQLite example lets you run the queries, see exactly where the cursor lands and test what happens when a new post arrives at the top.

Download the SQLite keyset pagination demo (ZIP). It includes the database fixture, the Python runner, the tests and a README.

Create the fixture and index

Use Python 3.10 or later with the standard sqlite3 module and SQLite 3.15.0 or later for row value comparisons. Open a terminal in the extracted sqlite-keyset-feed folder. If your system uses python3, substitute it in the commands below. The runner creates a fresh in-memory database each time.

Save this fixture as schema.sql. The feed sorts by created_at DESC, id DESC. When two timestamps match, the larger ID comes first. The index uses the same column order and directions. The timestamps in this fixture are fixed-width UTC strings, so their text order agrees with chronological order. If your input contains different offsets or inconsistent precision, normalize it before you rely on that ordering.

CREATE TABLE posts (
    id INTEGER PRIMARY KEY,
    created_at TEXT NOT NULL,
    title TEXT NOT NULL
);

CREATE INDEX posts_feed_idx ON posts(created_at DESC, id DESC);

INSERT INTO posts (id, created_at, title) VALUES
    (1, '2026-11-18T09:00:00Z', 'Morning notes'),
    (2, '2026-11-18T10:00:00Z', 'Release checklist'),
    (3, '2026-11-18T10:00:00Z', 'Build results'),
    (4, '2026-11-18T10:00:00Z', 'Team update'),
    (5, '2026-11-18T11:00:00Z', 'Lunch break'),
    (6, '2026-11-18T12:00:00Z', 'Afternoon notes');

Carry the last visible row forward

The first query needs only the sort order and a limit. The next query uses (created_at, id) < (?, ?). SQLite compares the pair from left to right. For a cursor of (10:00, 3), anything earlier than 10:00 qualifies, and a row at exactly 10:00 qualifies if its ID is smaller than 3. That is how ID 2 reaches the third page. Because both columns sort in descending order, the comparison is strictly less than. Including equality would show the cursor row again.

Both queries ask for one extra row to see if another page exists. The extra row stays off the current page. Build the cursor from the last row you actually show. If you use the extra row as the cursor instead, the strict comparison excludes it on the next request. The SQL parameters bind the timestamp, ID and limit as values.

Save the runner as feed.py.

import argparse
from contextlib import closing
from pathlib import Path
import sqlite3

Cursor = tuple[str, int]
Post = tuple[int, str, str]


def seed(connection: sqlite3.Connection) -> None:
    schema = Path(__file__).with_name("schema.sql")
    connection.executescript(schema.read_text(encoding="utf-8"))


def read_page(
    connection: sqlite3.Connection,
    size: int,
    after: Cursor | None = None,
) -> tuple[list[Post], Cursor | None]:
    if not 1 <= size <= 100:
        raise ValueError("page size must be between 1 and 100")

    if after is None:
        rows = connection.execute(
            """
            SELECT id, created_at, title
            FROM posts
            ORDER BY created_at DESC, id DESC
            LIMIT ?
            """,
            (size + 1,),
        ).fetchall()
    else:
        rows = connection.execute(
            """
            SELECT id, created_at, title
            FROM posts
            WHERE (created_at, id) < (?, ?)
            ORDER BY created_at DESC, id DESC
            LIMIT ?
            """,
            (*after, size + 1),
        ).fetchall()

    visible = rows[:size]
    if len(rows) <= size:
        return visible, None

    last_id, last_time, _ = visible[-1]
    return visible, (last_time, last_id)


def main() -> None:
    parser = argparse.ArgumentParser(description="Page through a sample SQLite feed.")
    parser.add_argument("--size", type=int, default=2)
    args = parser.parse_args()

    with closing(sqlite3.connect(":memory:")) as connection:
        seed(connection)
        cursor = None
        page_number = 1
        while True:
            try:
                posts, cursor = read_page(connection, args.size, cursor)
            except ValueError as error:
                parser.error(str(error))
            print(f"Page {page_number}: " + ", ".join(str(row[0]) for row in posts))
            if cursor is None:
                break
            print(f"  next cursor: {cursor[0]} / {cursor[1]}")
            page_number += 1


if __name__ == "__main__":
    main()

Run the demo

python feed.py
python -m unittest -v

The default run prints the following IDs and cursors. After the third page, the runner stops because there was no extra row.

Page 1: 6, 5
  next cursor: 2026-11-18T11:00:00Z / 5
Page 2: 4, 3
  next cursor: 2026-11-18T10:00:00Z / 3
Page 3: 2, 1

Try python feed.py --size 1 to see each ID arrive once. An empty result has no next cursor. The runner rejects a size of zero, a negative size or a size above 100 with a usage error. The ZIP tests cover the timestamp tie, empty and short pages, size limits, an insert above the cursor and deletion of the cursor row.

What changes between requests

If a new post arrives above the cursor, opening the first page again shows it. Continuing from the saved cursor still asks for rows below the same pair. Deleting the cursor row also leaves the comparison usable because the next query uses the saved values directly. Separate page requests each read the feed as it exists at that moment. If a post changes its timestamp between requests it can move across the boundary, and newly inserted older posts can still appear later. Keep feed sort keys stable when that behavior matters.

This example supports forward traversal. If the interface needs jumping directly to page 50, it needs a different way to find the starting position. When adapting the query, keep any filters the same across pages and inspect the plan for the actual filter and sort. The sample index serves the shown feed; a filtered feed can have different index needs.

On SQLite 3.53.1, EXPLAIN QUERY PLAN reported a search using posts_feed_idx for the sample's next page, with no separate sort step. That observation is for this fixture and query. Check the plan again if you change the filters or index.

References include SQLite row values and scrolling queries, SQLite query planning and Python's sqlite3 reference.