Why does OFFSET pagination get slow in PostgreSQL?

OFFSET n does not skip rows cheaply. PostgreSQL still produces all n rows and then throws them away, so cost grows linearly with the page number: page 5,000 does 5,000 pages of work. In EXPLAIN ANALYZE it shows as a Limit node whose child reports far more rows than the query returned.

Key facts

| Fact | Value | |---|---| | What OFFSET actually does | "The rows skipped by an OFFSET clause still have to be computed inside the server" — LIMIT and OFFSET | | Cost shape | O(offset): linear in the page number, not constant per page | | Measured, 2M-row table, PostgreSQL 18, warm | OFFSET 0 → 4 buffers / 0.03 ms; OFFSET 100000 → 2,026 buffers / 7.9 ms; OFFSET 500000 → 10,116 buffers / 57 ms | | Keyset equivalent, same table | 4-5 buffers and ~0.1 ms at any depth | | Stability | OFFSET results shift when rows are inserted or deleted between requests — the docs warn of "an inconsistent set of a query's rows" | | Row-value comparison | (a, b) < (c, d) is a single row constructor comparison, usable as an index condition | | BUFFERS default | On with EXPLAIN ANALYZE since PostgreSQL 18 — EXPLAIN | | Fleet | Across 50 monitored instances, 86% are not capturing plans automatically, so the deep-page plan is usually never recorded |

Why this happens

LIMIT/OFFSET is a node on top of a plan, not a way into the middle of one. The docs are direct: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." The executor pulls rows from the child node one at a time, discards the first n, then passes the next limit rows up. Nothing lets it say "start at the 100,000th matching entry" — a B-tree is searched by key, not by ordinal position — so reaching row 100,000 means walking past 99,999 of them.

That is the problem everybody knows about. The second gets far less attention and, in a user-facing list, usually does more damage: OFFSET pagination is not stable.

Page 1 is a snapshot. By the time the user clicks "next", other sessions have inserted and deleted rows, and page 2 is computed against the current table. One row inserted ahead of the window shifts everything down by one, so the last item of page 1 reappears at the top of page 2. One row deleted, and an item slides up past the boundary and is never shown. No error is raised; the list simply lies. The docs make the same point from the ordering angle: without a total ordering you "may get an inconsistent set of a query's rows" across repeated LIMIT/OFFSET calls.

Adding a tiebreaker to ORDER BY fixes the equal-keys half of that, not the shifting-window half. Only a scheme that carries a position in key space rather than a count of rows skipped does that.

How to detect it

The tell in EXPLAIN ANALYZE is an arithmetic mismatch: a Limit node reports rows=20, and its child reports rows=100020. Every plan below was captured on a throwaway PostgreSQL 18 container against a 2,000,000-row events table (id bigserial primary key, created_at timestamptz, payload text, 256 MB, one index on (created_at DESC, id DESC), vacuumed and analysed), at stock settings (jit=on, max_parallel_workers_per_gather=2, shared_buffers=128MB) and run twice for a warm cache. No parallel plan was chosen:

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, created_at, payload
FROM events
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;
 Limit (actual time=9.352..9.356 rows=20.00 loops=1)
   Buffers: shared hit=2026
   ->  Index Scan using events_created_at_id_desc on events
          (actual time=0.023..7.311 rows=100020.00 loops=1)
         Index Searches: 1
         Buffers: shared hit=2026
 Execution Time: 9.372 ms

Everything is "correct": an index exists, it is used, there is no sort and no sequential scan. The query is still doing 5,000 times the work it needs to. rows=100020.00 under a rows=20.00 parent is the whole diagnosis; Buffers: shared hit=2026 is the cost in pages touched. BUFFERS is included by default with ANALYZE from PostgreSQL 18; on older versions ask for it explicitly. The rest of a plan's shape is covered in the hub, Reading PostgreSQL EXPLAIN and EXPLAIN ANALYZE output.

The same query at four depths, warm cache, same instance:

| Offset | Rows from child | Buffers | Time | |---|---|---|---| | 0 | 20 | 4 | 0.03 ms | | 10,000 | 10,020 | 206 | 1.4 ms | | 100,000 | 100,020 | 2,026 | 7.9 ms | | 500,000 | 500,020 | 10,116 | 57 ms |

Straight-line growth — and this is the good case, an index-ordered scan with no sort. Where the ORDER BY is not indexed, every page also pays for a full sort.

A collected plan for a deep OFFSET where the scan under the Limit node reads and discards far more rows than it returns.

The catch is catching the deep page. A paginator's pg_stat_statements row averages page 1 with page 5,000, so the mean looks unremarkable. Across 50 MyDBA-monitored instances, 86% have no automatic plan capture configured, so the slow page's plan is typically never recorded — see capturing slow-query plans automatically.

How MyDBA shows this

A LIMIT/OFFSET query template on the Queries page whose mean time climbs with the page number its samples reveal.

The Queries page sorts query templates by Total Time alongside Calls, Avg Time and Max Time, and a paginating query has a recognisable shape in those four columns: a high call count, an Avg Time that looks acceptable, a Max Time an order of magnitude above it, and a Total Time that keeps climbing anyway. That Avg/Max gap is the deep pages hiding inside the average — the Slow now lens filters on the current-window mean, so it often misses them, while sorting by Total Time surfaces them. Opening the template shows the collected parameter samples — the actual OFFSET values your application sends. If the largest is in the tens of thousands, the plan above is what is running. The free PostgreSQL health check collects the same per-template totals on your own database.

How to fix it

Keyset pagination (or seek pagination) replaces "skip 100,000 rows" with "start after this key": the client carries the sort-key values of the last row it displayed, and the next query starts there. The ordering must be total — no two rows may tie — so pair your sort column with the primary key, then use a row constructor comparison:

-- page 1
SELECT id, created_at, payload
FROM events
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- every later page: $1, $2 are the last row's created_at and id
SELECT id, created_at, payload
FROM events
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;

Write it as a row comparison, not the expanded boolean. (created_at, id) < ($1, $2) is a row constructor comparison: PostgreSQL treats it as one comparison against the composite key and can push it into the index as an Index Cond. The expansion most people write by hand — created_at < $1 OR (created_at = $1 AND id < $2) — is logically equivalent and plans much worse, because the OR becomes a Filter applied after the scan rather than a starting point for it. Same table, same index, same target row:

-- (created_at, id) < ($1, $2)
 Limit (actual time=0.032..0.034 rows=20.00 loops=1)
   Buffers: shared hit=3 read=1
   ->  Index Scan using events_created_at_id_desc on events (rows=20.00)
         Index Cond: (ROW(created_at, id) < ROW($1, $2))
 Execution Time: 0.104 ms

-- created_at < $1 OR (created_at = $1 AND id < $2)
 Limit (actual time=8.194..8.197 rows=20.00 loops=1)
   Buffers: shared hit=2026
   ->  Index Scan using events_created_at_id_desc on events (rows=20.00)
         Filter: ((created_at < $1) OR ((created_at = $1) AND (id < $2)))
         Rows Removed by Filter: 100000
 Execution Time: 8.215 ms

Rows Removed by Filter: 100000 — the OR form reproduced the OFFSET behaviour exactly, with extra words. Index Cond versus Filter is the whole game here: see what Filter means in an EXPLAIN plan and WHERE clause optimisation.

The index has to match the ordering. For the query above:

CREATE INDEX events_created_at_id_desc ON events (created_at DESC, id DESC);

A plain (created_at, id) index also works here, because a B-tree can be scanned backwards when every column reverses together — the plan reads Index Scan Backward. Mixed directions break it: order by created_at DESC, id ASC against that index and the planner adds an Incremental Sort, so every page pays for a sort again. The same applies to NULLS placement; CREATE INDEX accepts NULLS FIRST/NULLS LAST and it must match the ORDER BY, since DESC implies NULLS FIRST while ASC implies NULLS LAST. Keep the sort key non-nullable if you can. See how B-tree indexes work, and covering indexes for serving the page without heap access.

What keyset cannot do, stated honestly: jump to an arbitrary page number, or show "page 3 of 412". Both need a count of rows you have not visited. The first is usually fine — infinite scroll, "load more" and next/previous links need no page numbers, and nobody navigates 400 pages by ordinal. The second runs into a separate problem: an exact COUNT() over a filtered set is itself a full scan, which is why COUNT(\) is slow. An estimate, or no count at all, usually serves better.

Hybrid, for admin UIs that genuinely need page numbers. Cap the jump: offer numbered pages only for the first N, where the OFFSET is small and cheap, and switch to keyset beyond that. For date-ordered data, letting the user jump by value — a date picker seeding the keyset cursor — gives the same affordance without an OFFSET.

Cursors are the third option, within a single session. DECLARE opens a cursor over the query and FETCH pulls the next batch, so the server keeps the position and no rows are recomputed; WITH HOLD also fixes the result at commit time, making it stable. The cost is that you hold a connection (and, without WITH HOLD, a transaction) open for the whole browsing session — usually a bad trade for a web request pool, often the right one for a batch job or server-side export.

How to prevent it

FAQ

Is a large OFFSET slow even when the ORDER BY is fully indexed?

Yes. The index removes the sort, not the skipping. Every query measured above used an index-ordered scan with no sort node, and OFFSET 500000 still touched 10,116 buffers and took 57 ms warm, against 4 buffers and 0.1 ms for the keyset equivalent. An unindexed ORDER BY makes it worse, but indexing alone does not fix OFFSET.

Why is (a, b) < ($1, $2) faster than the equivalent OR condition?

Because PostgreSQL can use the row constructor comparison as an Index Cond — a starting point in the B-tree — while the OR form becomes a Filter applied to rows the scan has already produced. On the same table and index, the OR version reported Rows Removed by Filter: 100000 and 2,026 buffers; the row-value version, 20 rows and 4 buffers, for identical results.

How do I show a total page count with keyset pagination?

You mostly do not, and that is usually acceptable. If a number is genuinely required, use an estimate from pg_class.reltuples or the planner's row estimate rather than an exact COUNT(), which scans every matching row — see why COUNT(\) is slow in PostgreSQL. Reserve exact counts for small filtered sets where they are cheap by construction.

Does keyset pagination fix the duplicate/missing row problem too?

Partly, and better than OFFSET does. Because the cursor is a position in key space, concurrent inserts and deletes elsewhere do not shift your window, so the page-1 duplicate does not happen. You can still miss a row inserted behind the cursor after you passed it; only a cursor or a repeatable-read snapshot gives a fully fixed result set. This depends on a total ordering — if your sort column is not unique, append the primary key to the ORDER BY, the row comparison and the index, or the cursor will skip or repeat rows at every tie.

Part of the Reading PostgreSQL EXPLAIN and EXPLAIN ANALYZE Output guide. Last verified against PostgreSQL 18, 2026-09-17.