Sub topic 12
Why large offsets get slow
This chapter explains why OFFSET gets slower as the number grows, how to see that cost in a query plan, and what you can do about it. It assumes you can write SELECT, WHERE, and ORDER BY queries, and that you have already used LIMIT and OFFSET to build a paged query. It also assumes you know that an index is a sorted structure the database can search quickly.
The cost is hidden in the word "skip"
Here is the page-3 query from the previous chapter:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;It reads as "jump to row 21 and return 10 rows." The database cannot jump. Rows in a result set have no position until the sort order is applied, so the database has to produce rows 1 through 30 in order and throw away the first 20. The same query with OFFSET 2000000 has to produce 2,000,010 rows and discard 2,000,000 of them.
The work grows with the offset, not with the page size. Page 1 and page 100,000 return the same 10 rows to the client, but page 100,000 does about 100,000 times more work inside the database.
Two situations with different costs
How slow a large offset is depends on whether the database can produce rows already in the requested order.
No usable index: sort everything
If no index matches the ORDER BY, the database reads the whole table (after any WHERE filter), sorts all the rows, and then walks to the offset. The sort cost is paid on every page request, and it does not depend on the offset at all. Page 1 is already expensive. Many databases can shorten the sort for small LIMIT values by keeping only the top N rows in memory (a "top-N heapsort"). That trick works against you as the offset grows, because N is OFFSET + LIMIT. At an offset of two million, the top-N buffer is two million rows and may spill to disk.
A matching index: walk and discard
Suppose an index exists on the sort columns:
CREATE INDEX idx_orders_date_id ON orders (order_date DESC, order_id DESC);The database can now read index entries in the right order without sorting. Page 1 is fast because it reads 10 entries and stops. But the database still has to step over the skipped entries one by one, because an index is a tree ordered by key, not by row number. It has no way to ask "where is the 2,000,001st entry?" Often it must also visit the table row for each skipped entry, for example to apply a WHERE condition that the index does not cover. So the cost grows linearly with the offset, only with a smaller constant than the no-index case.
Seeing it in a query plan
Use EXPLAIN ANALYZE (PostgreSQL syntax, shown here) to compare actual row counts. The exact output differs by version and data, so read the shape, not the numbers.
EXPLAIN ANALYZE
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 1000000;In the plan, look at the node below Limit, typically an Index Scan or Sort. Its actual row count will be close to 1,000,010, while the Limit node outputs 10. The gap between those two numbers is the discarded work.
Other costs of deep paging
Speed is not the only problem with large offsets.
- Shifting pages. If a row is inserted or deleted between two page requests, every later row moves by one position. A user paging forward can see the same row twice, or miss one. This happens with any
OFFSETquery on a table that changes, and it gets more likely the longer a user takes to page through. - Memory and temp files. Deep offsets with a sort can use large amounts of working memory or spill to temporary files, which affects other queries on the same server.
- Unbounded requests. If the page number comes from a URL parameter, a client can request
OFFSET 900000000and force a very expensive query. Always validate and cap it.
Mitigations that keep OFFSET
Before replacing OFFSET, check whether a smaller change is enough.
- Add an index that matches the
WHEREandORDER BY. This removes the full sort and often lets the scan avoid reading table rows for skipped entries. - Cap the maximum page. Many search interfaces never need page 5,000. Limit the page number, or ask users to narrow the filter instead.
- Page over a narrow set first. Select only the keys with the offset, then fetch full rows for the 10 survivors:
SELECT o.order_id, o.order_date, o.total, o.customer_id
FROM orders AS o
JOIN (
SELECT order_id
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 1000000
) AS page ON page.order_id = o.order_id
ORDER BY o.order_date DESC, o.order_id DESC;The inner query can often be answered from the index alone, so the skipped entries never cause table lookups. The outer query fetches full rows for only 10 keys. This is called a deferred join. It lowers the constant factor but does not remove the linear growth: the database still steps over a million index entries. The outer ORDER BY is required, because a join does not promise to keep the subquery's order.
Removing the cost: seek instead of skip
The cost comes from counting rows to skip. If the client remembers the sort key of the last row it saw, the database can search for that key directly. This is keyset pagination, also called seek pagination, and the next chapter covers it fully. A short preview shows the idea:
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;With the index above, the database descends the index tree to the position of ('2024-03-15', 1042) and reads 10 entries from there. The cost is the same for page 1 and page 100,000, and rows inserted earlier in the order no longer shift the page you are on. The trade-off is that you lose random access: you can offer "next" and "previous", but not "jump to page 800", unless you combine it with other techniques.
Choosing between them
| Situation | Reasonable choice |
|---|---|
| Small table, or users rarely go past page 10 | Plain `LIMIT`/`OFFSET` |
| Users need "go to page N" | `OFFSET`, with an index, a page cap, and possibly a deferred join |
| Infinite scroll, feeds, API cursors, batch export | Keyset pagination |
| Data changes often while users page | Keyset pagination |
Common mistakes
- Testing on small data. An offset of 10,000 on a 50,000-row development table looks instant. Test with production-sized data, or read the plan.
- Sorting by a column with no index. The sort cost hits every page, not only deep ones.
- Missing tie-breaker. Without a unique final sort column such as
order_id, rows with equal sort values can appear in different orders between requests, which makes pages overlap or skip rows. - Using
COUNT(*)for the page total on every request. Counting all matching rows is also a full scan on large tables. Cache the count, estimate it, or drop the "page X of Y" display.
Exercise
A table events has 50 million rows and an index on (created_at, event_id). A report fetches page 400,000 with ORDER BY created_at, event_id LIMIT 100 OFFSET 39999900. The query takes seconds even though the index exists and only 100 rows are returned. Explain why, and name one change that keeps the cost the same for every page.
Show answer
The index gives rows in the right order, so no sort is needed, but the database still has to step over 39,999,900 index entries (often with table lookups) and discard them. An index cannot jump to a row number. The cost grows with the offset. Switching to keyset pagination fixes it: remember the last row's (created_at, event_id) and query WHERE (created_at, event_id) > (last_created_at, last_event_id) ORDER BY created_at, event_id LIMIT 100. The database then seeks directly into the index, so each page costs about the same.
Exercise
Why does a deferred join (selecting only keys with OFFSET in a subquery, then joining back to the table) speed up a deep page but not make it constant-time?
Show answer
The subquery can often be answered from the index alone, so skipped entries do not trigger table row lookups, and only the final 10 keys fetch full rows. That lowers the cost per skipped entry. The database still has to walk past every skipped index entry, so the work still grows linearly with the offset.