DAT-13Recommended
Page through long lists by key
For long lists, page by the last key seen instead of OFFSET. Offsets get slower with every page and skip or repeat rows when data changes.
How to do it
Sort by a unique key or a unique pair, index those columns in that order, and ask for rows after the last one shown. MySQL often skips the index for the row comparison below, so check its plan and write it there as created_at < $1 OR (created_at = $1 AND id < $2). Cap the page size on the server, as the resource limits rule says. The API playbook's cursor rule shows how clients receive the key.
Examples
SQL example
SELECT id, created_at, total_cents FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 50;
How to check
Follow the keys to a page 50,000 rows into a large list. It answers as fast as page 1, and its plan shows an index range scan.
Sources
Related rules
- API-21 Page lists with cursors in API design
- API-93 Cap the size of every request body in API design
- SCL-27 Change large tables in small batches in Scaling
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/queries-and-indexes/keyset-pagination">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.