IntermediateLesson 8 of 126 min read

Pagination, Filtering and Sorting: Offset Versus Keyset

Return big lists in pages without sending everything, compute page counts, filter and sort safely, and see the real difference between offset and keyset pagination when rows are inserted between requests.

In this lesson you will

  • Paginate with limit and offset
  • Compute total pages correctly
  • Paginate with a keyset cursor
  • Explain why offset can skip or repeat rows

About 28 minutes

The list that grew too long

Kofi’s library now has 237 tools, and the app’s first screen asks for all of them, which wastes the phone’s data and the server’s time. A back end returns long lists in pages, and the client asks for the next page when it needs it. The simplest method is limit and offset: the request says how many rows to return, the limit, and how many to skip, the offset, so page p of size s starts at offset (p – 1) x s. The response should also give the total number of rows, so the client can compute the number of pages, which is the total divided by the page size, rounded up.

Offset paging has two weaknesses. It gets slower for deep pages, because the database still has to walk past all the skipped rows. And it is unstable when the data changes: if a row is inserted at the beginning between the request for page 1 and the request for page 2, every row shifts by one, and the client sees the last row of page 1 again at the top of page 2, a duplicate, while deletions make rows disappear from view, a skip. Keyset pagination, also called cursor pagination, avoids both: the client sends the id of the last row it has seen, and the server returns the rows after it, using the index: WHERE id > :last ORDER BY id LIMIT :n. Filters work as extra WHERE conditions with parameters, and sorting must use an allow-list of column names, as in lesson 4.

Method Query Strength Weakness
Offset LIMIT 20 OFFSET 40 Jump to any page Slow when deep, unstable when data changes
Keyset WHERE id > 60 LIMIT 20 Fast and stable No jumping to page 7 directly
import sqlite3, json, math
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tools (id INTEGER PRIMARY KEY, name TEXT, kind TEXT)")
db.executemany("INSERT INTO tools VALUES (?,?,?)", [(i, "Tool %03d" % i, "power" if i % 3 == 0 else "hand") for i in range(1, 238)])
SORTS = {"id": "id", "name": "name"}
def page(n, size, kind=None, sort="id"):
    where, args = ("WHERE kind = ?", [kind]) if kind else ("", [])
    total = db.execute("SELECT COUNT(*) FROM tools " + where, args).fetchone()[0]
    rows = db.execute("SELECT id FROM tools %s ORDER BY %s LIMIT ? OFFSET ?" % (where, SORTS[sort]), args + [size, (n - 1) * size]).fetchall()
    return {"total": total, "pages": math.ceil(total / size), "ids": [r[0] for r in rows]}
p1, p10, p12 = page(1, 20), page(10, 20), page(12, 20)
power = page(1, 20, kind="power")
print("page 1 :", p1["ids"][:3], "...", p1["ids"][-1], "| total", p1["total"], "| pages", p1["pages"])
print("page 12:", p12["ids"], "(last page is short)")
print("power tools:", power["total"], "in", power["pages"], "pages; first ids", power["ids"][:4])

def offset_walk(insert_between):
    seen, n = [], 1
    while True:
        ids = [r[0] for r in db.execute("SELECT id FROM tools ORDER BY id LIMIT 50 OFFSET ?", [(n - 1) * 50])]
        if not ids: break
        seen += ids
        if n == 1 and insert_between: db.execute("INSERT INTO tools VALUES (?,?,?)", (0, "Early addition", "hand"))
        n += 1
    return seen
def keyset_walk(insert_between):
    seen, last, first = [], -1, True
    while True:
        ids = [r[0] for r in db.execute("SELECT id FROM tools WHERE id > ? ORDER BY id LIMIT 50", [last])]
        if not ids: break
        seen += ids; last = ids[-1]
        if first and insert_between: db.execute("INSERT INTO tools VALUES (?,?,?)", (-1, "Another early addition", "hand")); first = False
    return seen
off = offset_walk(True)
db.execute("DELETE FROM tools WHERE id IN (0, -1)")
key = keyset_walk(True)
dup = sorted({x for x in off if off.count(x) > 1})
missing = sorted(set(range(1, 238)) - set(off))
print("offset paging with an insert between pages: repeated ids", dup, "| rows seen", len(off))
print("keyset paging with an insert between pages: repeated ids", sorted({x for x in key if key.count(x) > 1}), "| missing ids", sorted(set(range(1, 238)) - set(key)), "| rows seen", len(key))
print("DATA " + json.dumps({"p1": p1, "p10": p10["ids"][:1], "p12": p12, "power": power, "dup": dup, "offn": len(off), "keyn": len(key), "keymissing": sorted(set(range(1, 238)) - set(key)), "keydup": sorted({x for x in key if key.count(x) > 1})}))
page 1 : [1, 2, 3] ... 20 | total 237 | pages 12
page 12: [221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237] (last page is short)
power tools: 79 in 4 pages; first ids [3, 6, 9, 12]
offset paging with an insert between pages: repeated ids [50] | rows seen 238
keyset paging with an insert between pages: repeated ids [] | missing ids [] | rows seen 237

With 237 tools and 20 per page there are 12 pages, because 237 / 20 = 11.85 rounds up to 12. Page 1 starts at id 1, page 10 starts at id 181 (9 x 20 + 1), and page 12, the last, is short, with 17 tools. A filter by kind narrows the list before paging: 79 of the tools are power tools (every third id), which makes 4 pages. Sorting used a dictionary of allowed names, so the client’s sort value never reaches the SQL text.

The second half is the experiment. While the client walked through the list in pages of 50, a new tool was inserted at the very beginning after page 1 was fetched. With offset paging, every later row shifted by one position, so the last row of page 1 appeared again at the top of page 2: the repeated ids were [50]. With keyset paging, the client asked for “rows after id 50”, and the insert at the front changed nothing: no row was repeated (0 repeats) and no row was missed (0 missing), and the walk saw exactly 237 rows. The newly inserted tool sits before the cursor, so this walk did not show it, which is right: it will appear when the client refreshes the list from the start. A deletion between pages would make offset paging skip a row in the same way. For a feed that changes while people scroll, keyset paging is the right choice, and for a stable report where users jump to page 7, offset is fine.

Independent check: the pages were also computed in plain Python by slicing a list of the same ids, and the first, tenth and last pages, the page count and the filtered list all agree with the database. The repeated id was found by counting the ids that were seen twice, and the missing ids by subtracting the ids seen from the set of all ids, which is independent of the SQL.

Check by hand: 237 divided by 20 is 11 remainder 17, so there are 11 full pages and a twelfth with 17 tools. Page 10 skips 9 x 20 = 180 rows, so it starts with id 181. A third of 237 is 79, so there are 79 power tools, and 79 / 20 = 3.95 rounds up to 4 pages.

Always set a maximum page size

If the client can ask for limit=1000000, one request can bring the server down. Clamp the limit to a safe maximum, such as 100, and use a sensible default.

Return the paging information in the response

Include the total (or a flag for “more”), the page size and a link or cursor for the next page. A client then needs no guesswork and no arithmetic.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. Keyset paging on a non-unique sort column needs a tiebreaker, for example the pair (created_at, id), so check your database documentation for row-value comparisons.

Practice

Add a next_cursor field to the response. Cap the limit at 100 and test limit=1000. Implement keyset paging sorted by name, using the pair (name, id) as the cursor.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

How many pages are there for 237 rows at 20 per page?

  1. 12
  2. 11
  3. 13
  4. 10

Round up.

What is a weakness of offset paging?

  1. It cannot sort
  2. It needs no index
  3. It limits pages to 10
  4. Rows can repeat or be skipped when data changes

And deep pages are slow.

What does keyset paging send instead of an offset?

  1. The page number
  2. The total
  3. A password
  4. The last id seen

WHERE id > :last.

How should the sort column be handled?

  1. Paste it into the SQL
  2. Ignore it
  3. Check it against an allow-list
  4. Hash it

Names cannot be parameters.

Why cap the page size?

  1. To save disk
  2. To sort faster
  3. To protect the server from huge requests
  4. It is required by SQL

Always clamp the limit.

Summary

  • Page with limit and offset, and compute pages by rounding up.
  • Offset paging can repeat or skip rows when data changes.
  • Keyset paging with the last id is stable and fast.
  • Allow-list sorts and cap the page size.

Next lesson

Lesson 9 covers caching and conditional requests.

Questions

Should I return the total count?

It is useful for page links, but counting a huge table can be slow. Some APIs return only whether there is a next page. Choose according to the size of your data.

What about sorting by a column that is not unique?

Add a unique tiebreaker such as the id, or rows with equal values can be repeated or skipped between pages.

Can I combine filters and keyset paging?

Yes. Add the filter to the WHERE clause and keep the cursor condition, with an index that matches both.

Progress is saved in this browser.