Sub topic 3
Building paged queries
This chapter assumes you know SELECT, FROM, WHERE, and ORDER BY, and that you can write a query that returns rows. You will combine DISTINCT, ORDER BY, LIMIT, and OFFSET into page-by-page queries.
Where each clause runs
Databases evaluate a query in a fixed order, regardless of how you write it. Filtering comes first, then column selection, duplicate removal, sorting, and finally the row window.
Because DISTINCT runs before ORDER BY and LIMIT, this query removes duplicates, sorts the unique countries, and then returns rows 6 to 10:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;Building a page
A page is a fixed-size window over a sorted result. Page 3 with a page size of 10 skips 20 rows:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;The order_id column breaks ties. Without a unique tie-breaker, rows with equal dates can move between pages.
Why large offsets get slow
OFFSET n makes the database read and discard n rows before it returns anything. Page 1000 at size 10 discards 9,990 rows, so the cost grows with the page number.
Keyset pagination
Keyset (seek) pagination remembers the last row of the previous page and asks for rows after it. The database can use an index to jump straight to that point:
SELECT order_id, order_date, total
FROM orders
WHERE (order_date, order_id) < ('2024-03-15', 1042)
ORDER BY order_date DESC, order_id DESC
LIMIT 10;This row-value comparison works in PostgreSQL, MySQL, and SQLite 3.15 or later.
Dialect syntax
| Database | First N rows | Skip and take |
|---|---|---|
| PostgreSQL, MySQL, SQLite | LIMIT 10 | LIMIT 10 OFFSET 20 |
| SQL Server | SELECT TOP 10 | OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY |
| Oracle 12c+ | FETCH FIRST 10 ROWS ONLY | OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY |
Exercise
A table has 500,000 orders. Why is LIMIT 10 OFFSET 499990 slow, and which keyset query would fetch the same 10 rows faster?
Show answer
The database reads and discards 499,990 rows before returning 10. Keyset pagination with the last seen (orderdate, orderid) pair avoids the skip: WHERE (order_date, order_id) < (last_date, last_id) ORDER BY order_date DESC, order_id DESC LIMIT 10.