Why does OFFSET pagination duplicate or skip rows on live feeds?
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:
| id | ts |
|---|---|
| 4 | 10:04 |
| 3 | 10:03 |
| 2 | 10:03 |
| 1 | 10:02 |
Page 1 returns IDs [4, 3].
- Before page 2 loads, post
(5, '10:05')is inserted. What doesOFFSET 2return, and what happens if post4is deleted instead? - Why does
WHERE ts < '10:03'still lose a post here? - Implement keyset (cursor) pagination using
(ts, id)and an opaque base64url cursor token.
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)
- "SHIFT UNDER OFFSET"
Inserting post
5pushes[4, 3]down by one slot. Skipping the first two rows now lands on post3again. - "BREAK TIMESTAMP TIES"
Posts
3and2share10:03. Filtering only onts < '10:03'skips post2completely. - "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.
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])
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 order | OFFSET 2 page 2 | Keyset (ts, id) < ('10:03', 3) |
|---|---|---|---|
| None | 4, 3, 2, 1 | [2, 1] | [2, 1] |
Insert (5, '10:05') | 5, 4, 3, 2, 1 | [3, 2] (dup 3) | [2, 1] |
Delete id = 4 | 3, 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:
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 ASCwhile using(ts, id) < (?, ?). Row-value comparison requires matching sort directions on both columns, or an explicitORclause. - 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 sizeand assuming another page exists wheneverlen(rows) == size. Fetchsize + 1rows, returnsize, and sethas_morefrom the extra row.
Follow-up questions
- "How do you know whether a next page exists without running COUNT(*)?" Query
LIMIT size + 1. If you getsize + 1rows back, sethas_more = true, drop the extra row, and buildnext_cursorfrom thesize-th row. Otherwise returnnext_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 row3by existence; it compares values in the index and starts right at post2.
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 →