download

Why does OFFSET pagination duplicate or skip rows on live feeds?

Backend~11 minReviewed 3 Dec 2026Free · No sign-in

Question

A feed shows newest posts first (ORDER BY ts DESC, id DESC) using LIMIT 2 OFFSET 2 for page 2. The table starts with four rows:

idts
410:04
310:03
210:03
110:02

Page 1 returns IDs [4, 3].

  1. Before page 2 loads, post (5, '10:05') is inserted. What does OFFSET 2 return, and what happens if post 4 is deleted instead?
  2. Why does WHERE ts < '10:03' still lose a post here?
  3. Implement keyset (cursor) pagination using (ts, id) and an opaque base64url cursor token.
"CODE · PYTHON"
def page(db, size, offset=0):
    sql = "SELECT id, ts FROM posts ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?"
    return [r[0] for r in db.execute(sql, (size, offset)).fetchall()]
Show hints (3)
  1. "SHIFT UNDER OFFSET"

    Inserting post 5 pushes [4, 3] down by one slot. Skipping the first two rows now lands on post 3 again.

  2. "BREAK TIMESTAMP TIES"

    Posts 3 and 2 share 10:03. Filtering only on ts < '10:03' skips post 2 completely.

  3. "ROW VALUE COMPARISON"

    Anchor on the last returned row with WHERE (ts, id) < (?, ?) and encode [ts, id] into an opaque base64url cursor.

Show checked explanation

OFFSET 2 counts positions from the top, so inserting post 5 duplicates post 3 ([3, 2]), while deleting post 4 skips post 2 ([1]). Anchor page 2 on the last item seen with WHERE (ts, id) < (?, ?) and pass [ts, id] inside an opaque base64url token.

"SOLUTION · PYTHON"
from base64 import urlsafe_b64decode as b64d, urlsafe_b64encode as b64e
import json
import sqlite3


def page(db, n, cur=None):
    k = json.loads(b64d(cur)) if cur else ()
    q = f"SELECT ts, id FROM posts {'WHERE (ts,id)<(?,?) ' if k else ''}"
    res = list(db.execute(q + "ORDER BY ts DESC, id DESC LIMIT ?", (*k, n)))
    tok = b64e(json.dumps(res[-1]).encode()).decode() if res else None
    return [r[1] for r in res], tok


db = sqlite3.connect(":memory:")
db.executescript(
    "CREATE TABLE posts (id INT PRIMARY KEY, ts TEXT);"
    "INSERT INTO posts VALUES (4,'10:04'),(3,'10:03'),(2,'10:03'),(1,'10:02')")
p1, tok = page(db, 2)
db.execute("INSERT INTO posts VALUES (5, '10:05')")
print("page1:", p1, "page2:", page(db, 2, tok)[0])
"OUTPUT"
page1: [4, 3] page2: [2, 1]

Ran the SQLite 3.49 keyset code, OFFSET insert/delete comparisons, timestamp-tie edge case, and EXPLAIN QUERY PLAN on CPython 3.12.10. Checked by an editor other than the author.

Walkthrough

OFFSET tells the database to sort the feed, walk past the first N rows, and discard them. Whenever rows enter or leave above your current spot, every row shifts index:

Change after page 1 ([4, 3])Table orderOFFSET 2 page 2Keyset (ts, id) < ('10:03', 3)
None4, 3, 2, 1[2, 1][2, 1]
Insert (5, '10:05')5, 4, 3, 2, 1[3, 2] (dup 3)[2, 1]
Delete id = 43, 2, 1[1] (skip 2)[2, 1]

Why a timestamp alone fails. Posts 3 and 2 share the same timestamp 10:03. Querying WHERE ts < '10:03' drops post 2 and returns only [1]. Pairing ts with a unique tiebreaker (id) makes every row position unique. Both SQLite and PostgreSQL evaluate the row-value comparison (ts, id) < ('10:03', 3) lexicographically: ts < '10:03' OR (ts = '10:03' AND id < 3).

Index speed at deep pages. Deep OFFSET 100000 still scans and discards 100,000 rows on every request. With a matching composite index, the engine seeks straight to the cursor key in logarithmic time:

"SQL"
CREATE INDEX idx_posts_ts_id ON posts (ts DESC, id DESC);

Keep the cursor opaque. Encoding ["10:03", 3] with base64url stops clients from parsing or hardcoding your sort columns. You can later swap sort keys or add a filter version without breaking callers. Validate and reject malformed cursors with 400 Bad Request.

Common mistakes

  • Paginating with WHERE ts < ? alone. Any two posts sharing the same millisecond or second get skipped across the page boundary.
  • Sorting by ts DESC, id ASC while using (ts, id) < (?, ?). Row-value comparison requires matching sort directions on both columns, or an explicit OR clause.
  • Letting clients build cursor strings themselves. Treat the cursor as an opaque token, and sign it with HMAC if tampering could bypass filters.
  • Fetching LIMIT size and assuming another page exists whenever len(rows) == size. Fetch size + 1 rows, return size, and set has_more from the extra row.

Follow-up questions

  • "How do you know whether a next page exists without running COUNT(*)?" Query LIMIT size + 1. If you get size + 1 rows back, set has_more = true, drop the extra row, and build next_cursor from the size-th row. Otherwise return next_cursor = null.
  • "When is OFFSET pagination still the right choice?" Small admin tables or static search views where users need random page jumps (Page 7 of 12) and deep offsets are capped. Keyset pagination cannot jump straight to page 7 without scanning.
  • "What happens if the row pointed to by the cursor gets deleted before page 2?" Keyset pagination still works cleanly. WHERE (ts, id) < ('10:03', 3) does not look up row 3 by existence; it compares values in the index and starts right at post 2.

What a strong answer covers

Traces how inserts duplicate rows and deletes skip rows under OFFSET. Uses a composite (ts, id) row-value keyset filter with a matching index, explains why timestamp ties break single-column cursors, and keeps tokens opaque.

Open in interactive practice deck →

Original OfferVibe question. PostgreSQL LIMIT and OFFSET · SQLite Row Values · SQLite SELECT.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.