Sub topic 8
Skipping rows with OFFSET
This chapter covers OFFSET, the clause that skips rows before LIMIT starts counting. It assumes you can write a SELECT with WHERE and ORDER BY, and that you know LIMIT returns at most N rows. Later chapters cover building complete paged queries, the cost of large offsets, and keyset pagination. This chapter covers the clause itself.
What OFFSET does
OFFSET n discards the first n rows of the ordered result. The rows that remain are then passed to LIMIT. With LIMIT 10 OFFSET 20, the database skips 20 rows and returns the next 10, which are rows 21 through 30 in the sort order.
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;This returns page 3 when the page size is 10. Pages 1 and 2 hold the 20 rows that are skipped.
The offset counts rows, not pages and not values. OFFSET 20 means "skip 20 rows". It does not mean "start at order 20" or "start at the 20th page".
Syntax and the order of clauses
OFFSET is written after ORDER BY. In PostgreSQL, MySQL, and SQLite, it is attached to LIMIT, and the two can appear in either order in PostgreSQL.
-- Both are valid in PostgreSQL
SELECT order_id FROM orders ORDER BY order_id LIMIT 10 OFFSET 20;
SELECT order_id FROM orders ORDER BY order_id OFFSET 20 LIMIT 10;MySQL and SQLite accept a shorthand form, LIMIT offset, count. The offset comes first, which is the opposite of the order in the words "limit, offset", so it is easy to misread.
-- MySQL and SQLite: skip 20 rows, return 10
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 20, 10;OFFSET without LIMIT
In PostgreSQL and in the standard OFFSET ... ROWS form, OFFSET can stand alone. The query then skips rows and returns all the rest.
SELECT order_id
FROM orders
ORDER BY order_id
OFFSET 100;MySQL and SQLite do not allow a bare OFFSET. Both require a LIMIT first. In MySQL, the documented workaround is a very large limit, such as LIMIT 18446744073709551615 OFFSET 100. In SQLite, LIMIT -1 OFFSET 100 means no limit.
OFFSET needs a deterministic ORDER BY
Relational tables have no inherent row order. Without ORDER BY, the database returns rows in whatever order is convenient, and that order can change between runs, after an update, or when the query plan changes. An offset applied to an unstable order skips an unpredictable set of rows.
Ties cause the same problem even with an ORDER BY. If several orders share an order_date, the database may order them differently from one execution to the next. A row near a page boundary can then show up on two pages, or on none.
-- Risky: many orders can share the same order_date
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC
LIMIT 10 OFFSET 20;
-- Safe: order_id breaks ties, so the order is total
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;A tie-breaker works when the combined sort columns are unique per row. A primary key such as order_id is the usual choice.
Edge cases
Values at the edges behave as follows.
| Situation | Result |
|---|---|
| `OFFSET 0` | Skips nothing. Same as omitting `OFFSET`. |
| Offset larger than the row count | Returns an empty result with no error. |
| Offset equal to the row count | Returns an empty result. |
| Fewer rows remain than the `LIMIT` | Returns the remaining rows, fewer than the limit. |
| Negative offset | An error in PostgreSQL and MySQL. Treated as 0 in SQLite. |
| `OFFSET NULL` | Treated as `OFFSET 0` in PostgreSQL. |
The last page of a paged result is the usual case where fewer rows come back than the limit. Application code can use this to detect the end: if a page returns fewer rows than the page size, there is no next page. If the total row count is an exact multiple of the page size, the next request returns zero rows, so handle an empty page as well.
OFFSET after DISTINCT
OFFSET applies to the rows that remain after DISTINCT removes duplicates. The skipped rows are unique values, not raw rows from the table.
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;The database removes duplicates, sorts the unique countries, skips the first 5, and returns the next 5. If 40 customers live in the same country, that country still counts as one row toward the offset.
Computing an offset from a page number
Applications usually think in page numbers and page sizes. The offset is derived from them:
offset = (page_number - 1) * page_sizeFor a page size of 10, page 1 uses OFFSET 0, page 2 uses OFFSET 10, and page 3 uses OFFSET 20. The next chapter builds this into complete paged queries. For now, note that the offset is always a multiple of the page size.
Here is a small runnable example that applies the formula, using Python and SQLite. Values go in as bound parameters, not string concatenation, so a page number from a user cannot change the query.
import sqlite3
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_id, order_date, total) VALUES (?, ?, ?)",
[(i, f"2024-03-{(i % 28) + 1:02d}", i * 1.5) for i in range(1, 51)],
)
def fetch_page(page_number, page_size=10):
offset = (page_number - 1) * page_size
return conn.execute(
"""
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT ? OFFSET ?
""",
(page_size, offset),
).fetchall()
for page in (1, 2, 6):
rows = fetch_page(page)
print(f"page {page}: {len(rows)} rows")Fifty rows with a page size of 10 give five full pages. Page 6 starts at offset 50, which equals the row count, so it returns 0 rows.
Rows can move between requests
OFFSET counts from the start of the result each time the query runs. It has no memory of earlier pages. If rows are inserted or deleted between two page requests, the rows shift.
Suppose a user views page 1 of orders sorted newest first. A new order arrives. When the user requests page 2 (OFFSET 10), every row has moved down by one position. The last row of page 1 is now the first row of page 2, so the user sees it twice. If a row is deleted instead, a row can be skipped and never shown.
Deterministic ordering does not prevent this. It only guarantees a stable order for a fixed set of data. Keyset pagination, covered later in this tutorial, avoids the problem by continuing from the last seen sort key.
The standard form: OFFSET ... FETCH
The SQL standard spells the same operation with OFFSET ... ROWS and FETCH. PostgreSQL, Oracle 12c and later, and SQL Server 2012 and later support 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;In SQL Server, this form requires an ORDER BY, and OFFSET is only allowed as part of that clause. Without an ORDER BY, the query fails. The next-to-last chapter in this tutorial compares these dialects in detail.
Common mistakes
- Using
OFFSETwith noORDER BY, so pages are arbitrary. - Sorting on a column with ties and no tie-breaker, so rows repeat or vanish across pages.
- Swapping the numbers in the MySQL form
LIMIT offset, count. - Computing the offset as
page_number * page_size, which skips the first page. - Building the query by concatenating user input into the SQL text instead of using bound parameters.
- Assuming a short page is always the last page, without handling an empty page.
Exercise
A table products has 95 rows and a unique product_id. You show 20 products per page, sorted by price ascending. Write the query for page 4, and say how many rows it returns. Then say what happens if price has many ties and your query sorts only by price.
Show answer
Page 4 has offset (4 - 1) * 20 = 60. The query is SELECT product_id, name, price FROM products ORDER BY price, product_id LIMIT 20 OFFSET 60;. Rows 61 to 80 exist, so it returns 20 rows. (Page 5 would return only 15 rows, rows 81 to 95.) If the query sorts only by price, rows with equal prices can come back in a different order on each run, so a product near a page boundary can appear on two pages or on none. Adding product_id as a tie-breaker makes the order total and the pages stable.
Exercise
In MySQL, what does LIMIT 5, 15 return, and how would you write the same query in the more readable form?
Show answer
It skips 5 rows and returns the next 15, because the first number in the comma form is the offset and the second is the row count. The readable form is LIMIT 15 OFFSET 5.