Sub topic 9
Building paged queries
Paging means returning a large result set in fixed-size slices, such as 10 orders per screen. This chapter assumes you can write a basic SELECT ... FROM ... WHERE, sort with ORDER BY, and that you already know LIMIT restricts the row count and OFFSET skips rows. Here you combine them into a working page query, handle the edge cases, and learn the errors that appear in real applications.
The page formula
A paged query needs two inputs from the application: the page number (starting at 1) and the page size. The database needs two values: how many rows to return and how many to skip.
LIMITequals the page size.OFFSETequals(page - 1) * page_size.
With a page size of 10, the offsets are:
| Page | Rows returned | OFFSET |
|---|---|---|
| 1 | 1 to 10 | 0 |
| 2 | 11 to 20 | 10 |
| 3 | 21 to 30 | 20 |
| 4 | 31 to 40 | 30 |
Page 3 of the orders list, newest first, looks like this:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;The query skips the first 20 rows in the sort order and returns the next 10. Page 1 is the same query with OFFSET 0, and you can also omit the OFFSET clause for it.
Why the ORDER BY decides everything
A table has no inherent row order. If you page without ORDER BY, the database may return rows in any order, and that order can differ between two runs of the same query. Page 2 might then repeat rows from page 1 or leave rows out.
A sort on a non-unique column is not enough either. Many orders can share one order_date. When rows tie, the database may place them in different orders each time, and a tied row can land on page 2 in one request and page 3 in the next. The fix is a tie-breaker: add a column that is unique, usually the primary key, as the last sort key.
ORDER BY order_date DESC, order_id DESCNow every row has exactly one position in the sort, so every page boundary falls in the same place for the same data.
A page query step by step
The sequence below shows what happens when the application requests page 3.
In application code, never build the SQL by pasting the page values into a string without checking them. Validate that the page number is a positive integer and cap the page size, then pass the values as query parameters. This sketch uses Python's built-in sqlite3 module:
import sqlite3
MAX_PAGE_SIZE = 100
def fetch_orders_page(conn, page, page_size):
page = max(1, int(page))
page_size = min(max(1, int(page_size)), MAX_PAGE_SIZE)
offset = (page - 1) * page_size
cur = conn.execute(
"""
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT ? OFFSET ?
""",
(page_size, offset),
)
return cur.fetchall()
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE orders (order_id INTEGER PRIMARY KEY, order_date TEXT, total REAL)")
conn.executemany(
"INSERT INTO orders (order_date, total) VALUES (?, ?)",
[(f"2024-03-{(i % 28) + 1:02d}", 10.0 + i) for i in range(45)],
)
print(fetch_orders_page(conn, 3, 10))The capped page size matters. A client that asks for page_size=1000000 would otherwise force the database to return the whole table.
Paging with DISTINCT
You can page over unique values too. DISTINCT runs before ORDER BY and LIMIT, so the database removes duplicates first, sorts what is left, and then slices it.
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;This returns the second page of five unique countries. The sort key here is the selected column, and it is unique after DISTINCT, so no extra tie-breaker is needed. If you select DISTINCT country, city, sort by both columns.
Some databases, PostgreSQL among them, require the ORDER BY expressions of a SELECT DISTINCT query to appear in the select list. You cannot select DISTINCT country and order by a column you did not select, because the order would be ambiguous: one country can have many values of that other column.
Finding out how many pages exist
A pager usually shows "page 3 of 12". The total page count needs a second query that counts all matching rows, with the same WHERE conditions as the page query:
SELECT COUNT(*) AS total_rows
FROM orders;The application then computes ceil(total_rows / page_size). For a distinct list, count the distinct values instead:
SELECT COUNT(DISTINCT country) AS country_count
FROM customers;Run the count and the page query inside one transaction if you need them to agree. Otherwise a row inserted between the two statements can make the count and the page content disagree.
A cheaper alternative avoids the count: request page_size + 1 rows. If you get the extra row back, a next page exists, and you drop that row before display. This supports "Next" and "Previous" buttons without the cost of counting a large table.
Common errors
Rows move between pages
Paging with OFFSET assumes the data stays still. If a new order is inserted at the top of the sort while the user reads page 1, every row shifts down by one. When the user opens page 2, its first row is the last row they already saw on page 1. Deleting a row shifts rows the other way, so a row is skipped and never shown. A stable sort fixes the tie problem, but it cannot fix changes in the data between requests. If this matters, use keyset pagination, which a later chapter covers.
Offset beyond the last row
An offset past the end of the result is not an error. The query returns zero rows. Treat an empty page as "no more data" in the application, and decide whether to redirect the user to the last valid page.
Page numbers of zero or below
With page 0 the formula gives (0 - 1) * 10 = -10. A negative offset raises an error in PostgreSQL and in some other databases. Clamp the page number to at least 1 before computing the offset, as the Python example does.
Missing tie-breaker
This is the most frequent cause of "duplicate rows on different pages" bug reports. Check that the final ORDER BY column is unique. A primary key is the usual choice.
Sorting on a computed or nullable column
If the sort column contains NULL, the position of those rows depends on the database. PostgreSQL and Oracle place NULL last in ascending order and first in descending order. MySQL and SQLite treat NULL as the smallest value. A consistent order within one database is fine for paging, but if the query might run on more than one system, state the rule explicitly where the dialect supports it:
SELECT order_id, shipped_date
FROM orders
ORDER BY shipped_date DESC NULLS LAST, order_id DESC
LIMIT 10 OFFSET 10;NULLS LAST works in PostgreSQL, Oracle, and SQLite 3.30 and later. MySQL and SQL Server do not support it.
The standard SQL form
LIMIT ... OFFSET ... is not part of the SQL standard. The standard spelling is shown below. It works in PostgreSQL, Oracle 12c and later, and SQL Server 2012 and later. SQL Server requires an ORDER BY for it.
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;The result is identical to LIMIT 10 OFFSET 20. A later chapter covers other dialect forms.
When OFFSET paging is the right choice
OFFSET paging suits small and medium result sets, pages the user reaches by number ("jump to page 7"), and internal tools where a slightly shifting list is acceptable. It becomes costly for deep pages, because the database still reads and discards every skipped row. A later chapter explains that cost and shows the keyset alternative:
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 query continues after the last row the user saw, so it does not skip anything.
Exercise
A product list is sorted by price and paged with LIMIT 20 OFFSET 40. Users report that some products appear on two pages and others never appear, even though no data changes. Many products share the same price. What is the cause, and how do you fix the query? Also, which page number does this query return?
Show answer
The sort key price is not unique, so rows with equal prices can be ordered differently on each request, which moves them across page boundaries. Add a unique tie-breaker as the last sort key, for example ORDER BY price, product_id. The offset 40 with page size 20 is page 3, because (3 - 1) * 20 = 40.
Exercise
Write a query that returns page 4 of the distinct city values from customers, in alphabetical order, with a page size of 25.
Show answer
SELECT DISTINCT city FROM customers ORDER BY city LIMIT 25 OFFSET 75; The offset is (4 - 1) * 25 = 75. The distinct values are unique, so ordering by city alone gives a deterministic result.