# Why does my Postgres query get slower as the table grows, even with an index?

By Vishal Kumar · Published 2026-11-07 · Updated 2026-11-13
Source: https://fungyaan.com/p/postgres-slow-query-table-growth
Tags: databases, postgres, performance, indexes

**The verdict, which six cases below will earn:** an index makes a query fast only when Postgres can stop early or touch few pages. As a table grows, six common things break that: the index matches your sort but not your filter, `OFFSET` makes Postgres read every row it skips, the rows you want are scattered across the table, statistics are stale, rows were updated without `VACUUM`, or deleted rows left the table as big as before. Run `EXPLAIN (ANALYZE, BUFFERS)` and watch the number of pages read, not only the time. Every one of these shows up there.

> **Case file**
>
> | | |
> |---|---|
> | **The case** | A query with an index was fast at launch and crawls a few million rows later |
> | **Suspects** | "Postgres is slow" |
> | **Culprit** | Six: sort-only index, `OFFSET`, scattered rows, stale statistics, no `VACUUM`, deleted rows on disk |
> | **The fix** | Composite indexes, keyset pagination, `ANALYZE`, autovacuum tuning, time partitions |
> | **Evidence** | PostgreSQL 17 at 10,000, 1,000,000 and 10,000,000 rows (`make slowquery`) |

## The case

The query was fast at launch. It has an index. Nobody touched it. And now, a year and a few million rows later, it crawls. The first suspect people name is always the same: "Postgres is slow". That suspect is never guilty. There's always a specific, explainable reason, and once you start counting pages instead of milliseconds, each culprit steps into the light.

I measured all six on PostgreSQL 17 at 10,000, 1,000,000 and 10,000,000 rows. The evidence is in [database-tradeoffs-lab](https://github.com/the-vishal-kumar/database-tradeoffs-lab/tree/main/02-slow-queries), and `make slowquery` reproduces every number below.

## The six culprits at a glance

Measured at 10 million rows. "Pages" are 8 KB buffers touched, which is a measure of work that doesn't depend on the machine. That makes it the most trustworthy witness we have.

| Cause | What `EXPLAIN` shows | Slow version | Fixed | Fix |
|---|---|---|---|---|
| 1. Index on the sort column, filter on another | `Index Scan` that reads far more rows than it returns | 1,513 ms · 216,402 pages | 0.06 ms · 7 pages | Composite index: `(tenant_id, created_at)` |
| 2. `OFFSET` pagination | `Limit` over a scan that reads offset + 20 rows | 189 ms · 21,862 pages | 0.04 ms · 4 pages | Keyset pagination |
| 3. Rows scattered across the table | `Bitmap Heap Scan`, roughly one page per row | 209 ms · 50,061 pages | 7.9 ms · 961 pages (same rows, in disk order) | Cluster, cover, or partition |
| 4. Stale statistics, in a join | Estimated rows ≪ actual rows; `Nested Loop` | 1,098 ms · 2,009,018 pages | 193 ms · 13,443 pages | `ANALYZE` |
| 5. Updates without `VACUUM` | `Index Only Scan` with `Heap Fetches` > 0 | 473 ms · 950,000 heap fetches | 129 ms · 0 heap fetches | `VACUUM` (autovacuum tuning) |
| 6. Deleted rows still on disk | `Seq Scan` reads the same pages after a big delete | 336 ms · 180,752 pages (1.4 GB) | 171 ms · 16,436 pages (128 MB) | `VACUUM FULL` / `pg_repack`, or partitions you can drop |

The test machine was a laptop (Intel i7-8550U, 8 threads, 10 GB RAM) running the official `postgres:17-alpine` image with default settings, so `shared_buffers` was 128 MB, smaller than the 1.4 GB table at 10M rows. The one change: parallel query was turned off, so every size is measured the same way. Times are medians of 5 runs after a warm-up, measured with `EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)` so per-node clock calls don't inflate row-heavy plans. A production server will be faster; the page counts won't change.

## 1. The index matches your sort, not your filter

**The scene:** a multi-tenant dashboard shows each customer their 20 latest orders. There's an index on `created_at` because "we sort by date".

```sql
SELECT id, created_at, total_cents
  FROM orders
 WHERE tenant_id = 7
 ORDER BY created_at DESC
 LIMIT 20;
```

Postgres walks the `created_at` index from the newest row and checks each row's tenant until it has 20 matches. That's fast for a big, active tenant. Tenant 7 is small and *old*: all its orders are in the first 1% of the table. So Postgres walks almost the whole index first.

| Rows in table | Index on `(created_at)` only | Index on `(tenant_id, created_at)` |
|---:|---|---|
| 10,000 | 0.45 ms · 164 pages (planner chose a table scan) | 0.07 ms · 4 pages |
| 1,000,000 | 134 ms · 21,649 pages | 0.04 ms · 7 pages |
| 10,000,000 | 1,513 ms · 216,402 pages | 0.06 ms · 7 pages |

The slow version grows with the table: 10× the rows, 10× the pages. The fixed version doesn't grow at all, because the composite index jumps straight to tenant 7's newest row. That's the elegant part: the cost stops depending on the table. **The rule: equality filters first in a composite index, then the sort column.** This is the most common culprit in multi-tenant SaaS, and the sneakiest: it's fine for your big tenants and slow only for small ones, so it hides from dashboards that average everything.

## 2. `OFFSET` reads everything it skips

**The scene:** an admin list with page numbers. A user jumps 10% of the way in.

```sql
-- OFFSET: reads and discards offset + 20 rows
SELECT id, created_at FROM orders ORDER BY created_at DESC OFFSET 1000000 LIMIT 20;

-- Keyset: starts right after the last row the user saw
SELECT id, created_at FROM orders WHERE created_at < $last_seen ORDER BY created_at DESC LIMIT 20;
```

| Rows in table | `OFFSET` (10% deep) | Keyset |
|---:|---|---|
| 10,000 | 0.15 ms · 25 pages | 0.03 ms · 3 pages |
| 1,000,000 | 13.4 ms · 2,192 pages | 0.04 ms · 7 pages |
| 10,000,000 | 189 ms · 21,862 pages | 0.04 ms · 4 pages |

```mermaid
xychart-beta
  title "OFFSET 10% deep vs keyset, ms"
  x-axis ["10,000 rows", "1,000,000 rows", "10,000,000 rows"]
  y-axis "ms"
  bar [0.15 , 13.4 , 189]
  bar [0.03 , 0.04 , 0.04]
```

The index can't skip a million entries; it has to step through them. Keyset pagination fixes it, and I love how simple the idea is: by remembering where you were instead of counting how far you've come, it costs the same on page 1 and on page 50,000. The trade-off: you lose "jump to page 7,431", which is rarely a real need. Infinite scroll, "next page" and API cursors all work with keyset. If the sort column isn't unique, make the cursor `(created_at, id)`.

## 3. The rows you want are scattered across the table

**The scene:** "total revenue for this customer range" vs "total revenue for this date range", each returning 0.5% of the rows.

| Rows in table | 0.5% of rows by `created_at` (follows disk order) | 0.5% of rows by `customer_id` (scattered) |
|---:|---|---|
| 10,000 | 0.03 ms · 5 pages | 0.12 ms · 52 pages |
| 1,000,000 | 0.72 ms · 100 pages | 4.1 ms · 5,017 pages |
| 10,000,000 | 7.9 ms · 961 pages | 209 ms · 50,061 pages |

This one surprises people. Same number of rows, 52× the pages. An index tells Postgres *where* the rows are; it still has to read the page each row lives on. When the rows were inserted together (by date), many share a page. When they're spread out (by customer), each row is its own page read. Postgres tracks this as **correlation** in `pg_stats`, and it's why the planner sometimes ignores an index you expected it to use.

Fixes, from cheapest: a **covering index** (`INCLUDE (total_cents)`) so the query never visits the table; `CLUSTER` to rewrite the table in index order (one-off, it drifts again as new rows arrive); or **partitioning** by the column you filter on.

## 4. Stale statistics, and why it matters in joins

**The scene:** a bulk job marks 5% of orders as `refunded`, a status that didn't exist when Postgres last sampled the table. Then a report runs before autovacuum's `ANALYZE` has caught up.

```sql
SELECT count(*)
  FROM orders o JOIN customers c ON c.id = o.customer_id
 WHERE o.status = 'refunded' AND c.country = 'NL';
```

| Rows in table | Orders only, stale | Joined, stale | Joined, after `ANALYZE` |
|---:|---|---|---|
| 1,000,000 | 7.3 ms · est. **1** row, actual 50,000 | 103 ms · 200,905 pages · `Nested Loop` | 96 ms · 5,330 pages · `Hash Join` |
| 10,000,000 | 79 ms · est. **1** row, actual 500,000 | 1,098 ms · 2,009,018 pages · `Nested Loop` | 193 ms · 13,443 pages · `Hash Join` |

This shows how much the planner relies on what it believes. On its own, the bad estimate looked like a red herring: both plans read the same pages. In the join it decided everything. Expecting 1 row, Postgres chose a nested loop, which means one index lookup into `customers` per order. With 500,000 orders that is 2 million page touches. After `ANALYZE` it knew the real count and chose a hash join. **The tell-tale clue in `EXPLAIN ANALYZE` is an estimate that's orders of magnitude off the actual rows.** Autovacuum analyses tables in the background, but after a bulk update, import or backfill, run `ANALYZE` yourself as the job's last step.

## 5. Updated rows send index-only scans back to the table

**The scene:** a dashboard counter, `count(*)` over a date range, normally answered from the index alone.

| Rows in table | After `VACUUM` | After updating 10% of rows, no `VACUUM` | After `VACUUM` again |
|---:|---|---|---|
| 1,000,000 | 8.7 ms · 0 heap fetches | 23.1 ms · 95,000 heap fetches | 9.7 ms · 0 |
| 10,000,000 | 114 ms · 0 heap fetches | 473 ms · 950,000 heap fetches | 129 ms · 0 |

An index doesn't know whether a row version is visible to your transaction; only the table does. The clever piece is the **visibility map**: an *index-only* scan can skip the table for pages it marks "all visible". Any update clears that mark for its page until `VACUUM` sets it again. Until then, every changed row costs a trip to the table: here, about 4× slower at 10M rows. A long-running transaction can stop `VACUUM` from doing this at all (the [long-transaction case](/p/long-transaction-slows-database)).

One honest loose end from the 10M run: after the updates and `VACUUM`, the scan was back to zero heap fetches but still touched more pages than before (302,736 vs 102,737) and was a little slower (129 ms vs 114 ms). Most likely those are visibility-map lookups. The updated rows had moved to the end of a 1.4 GB table, so consecutive index entries point into parts of the table covered by different visibility-map pages. At 1M rows the whole table sits under one visibility-map page, and the effect disappears.

On busy tables, the fix is usually **autovacuum tuning**: lower `autovacuum_vacuum_scale_factor` per table, so a 10M-row table is vacuumed after, say, 1% of rows change instead of the default 20% (PostgreSQL 17).

## 6. Deleting rows doesn't make the table smaller

**The scene:** a retention job deletes 90% of old orders, and a nightly report that scans the table doesn't get any faster.

| Rows in table (before delete) | Full table | After deleting 90% | After `VACUUM` | After `VACUUM FULL` |
|---:|---|---|---|---|
| 1,000,000 | 123 ms · 18,076 pages · 141 MB | 34.2 ms · 18,076 pages | 21.1 ms · 18,076 pages · 141 MB | 13.3 ms · 1,644 pages · 13 MB |
| 10,000,000 | 1,560 ms · 180,752 pages · 1.4 GB | 560 ms · 180,752 pages | 336 ms · 180,752 pages · 1.4 GB | 171 ms · 16,436 pages · 128 MB |

`DELETE` only marks rows dead, and `VACUUM` makes their space reusable for future inserts, but neither gives the space back. A scan still reads every page of a mostly empty 1.4 GB file. (It got faster after the delete because there are fewer live rows to count, but the pages read didn't change; the timing was a false lead.) `VACUUM FULL` rewrites the table and shrinks it by 90%, but it takes an exclusive lock for the whole rewrite. On a live system use [`pg_repack`](https://github.com/reorg/pg_repack), which does the same with only brief locks. Better still, if you delete by time, **partition by time** and drop old partitions: an instant, lock-light `DROP` instead of a huge `DELETE` (the [partitioning case](/p/replicas-partitioning-sharding) covers when partitions pay off).

## How to investigate your own slow query

`EXPLAIN` tells you which story you're in, if you know where to look:

1. Run it with `EXPLAIN (ANALYZE, BUFFERS)` on production-sized data. A plan from a 10,000-row staging table can be completely different, as the 10,000-row line of cause 1 shows.
2. Compare **rows returned** to **rows read** (`Rows Removed by Filter`, or `actual rows` on the scan). Reading far more than you return points to causes 1-3.
3. Compare **estimated** to **actual** rows on each node. Orders of magnitude apart means cause 4: `ANALYZE`.
4. For `Index Only Scan`, check **Heap Fetches**. Non-zero means cause 5: vacuum.
5. Check table size against live rows (`pg_relation_size` vs `count(*)`, or `pg_stat_user_tables.n_dead_tup`). A big gap means cause 6.

```mermaid
flowchart TD
  E["EXPLAIN (ANALYZE, BUFFERS)"] --> A{"Reads far more rows than it returns?"}
  A -->|yes| C13["Causes 1-3: index order, OFFSET, scattered rows"]
  A -->|no| B{"Estimate orders of magnitude off actual?"}
  B -->|yes| C4["Cause 4: ANALYZE"]
  B -->|no| H{"Heap Fetches above 0?"}
  H -->|yes| C5["Cause 5: VACUUM"]
  H -->|no| S{"Table far bigger than its live rows?"}
  S -->|yes| C6["Cause 6: VACUUM FULL, pg_repack, partitions"]
```

> **Remember this**
> - Count pages, not milliseconds.
> - Equality columns first in a composite index, then the sort column.
> - Every slow plan here was fast at 10,000 rows, so test on production-sized data.

## What I'd do on Monday

- Design composite indexes from the queries: **equality columns first, then the sort column**, and `INCLUDE` the columns you return if the query is hot.
- Use **keyset pagination** for anything users scroll or APIs page through.
- Make **`ANALYZE` the last step** of every bulk job, and tune autovacuum per table on anything over a few million rows.
- **Partition by time** any table you'll delete from by age.
- Test performance on **production-sized data**. Every slow plan above was fast at 10,000 rows.

Postgres is an honest witness. Every one of these slowdowns was sitting in plain sight in the page counts, waiting for someone to read them.

*Checked on PostgreSQL 17.11 (Nov 2026). Code, data generator and full results: [database-tradeoffs-lab/02-slow-queries](https://github.com/the-vishal-kumar/database-tradeoffs-lab/tree/main/02-slow-queries).*
