How do you implement pagination in SQL, and what are the trade-offs between OFFSET/LIMIT and keyset (seek) pagination?
Last updated
OFFSET/LIMITis simple and allows jumping to any page, but scans and discards skipped rows (slow on deep pages) and can duplicate or skip rows when data changes.Keyset (seek) pagination filters past the last-seen sort value (
WHERE (created_at, id) > (...)) using an index, giving constant speed and stability under inserts.Keyset cannot jump to arbitrary pages and needs an indexed, tie-broken sort key. Use it for APIs and infinite scroll, and offset for small paged tables.
- https://medium.com/@samurai.stateless.coder/offset-vs-keyset-pagination-postgres-5d35e64606dc
- https://www.trinitylogic.co.uk/blog/spring-data-keyset-pagination-java/
- https://mwaseemzakir.substack.com/p/offset-keyset-and-cursor-pagination
- https://medium.com/@dixitgurv/keyset-pagination-for-apis-building-scalable-consistent-paging-d6a8508eb642
- https://www.youtube.com/watch?v=XHQ8QhslXS0
- https://www.mironsoft.de/en/blog/sql-pagination-strategies-offset-vs-keyset
- https://dev.to/scion01/optimizing-pagination-in-postgresql-offsetlimit-vs-keyset-21dp
- https://www.stacksync.com/blog/keyset-cursors-postgres-pagination-fast-accurate-scalable