CHAPTER 9
Pagination — how every "Load More" button in every app works.
Top 3 earners
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;
Page 2 of employees (3 per page)
-- Page formula: OFFSET = (page_number - 1) * page_size SELECT name FROM employees ORDER BY name LIMIT 3 OFFSET 3; -- Page 2
✅ Pro Tip: Always include ORDER BY when using LIMIT/OFFSET. Without ORDER BY, the database returns rows in an arbitrary order — pagination results will be inconsistent and unpredictable across queries.
💡 Engineering Insight: At scale, OFFSET-based pagination is inefficient — to get page 1000 the database still reads 999*page_size rows and throws them away. Senior engineers use 'keyset pagination' (WHERE id > last_seen_id) which is O(1) regardless of page number.