---
title: "Is the slower PostgreSQL query on a new plan, reading more rows, or waiting? | Proofline"
description: "A PostgreSQL query that got ten times slower runs a different plan, runs the same plan over more rows, or spends the extra time waiting for a lock or for I/O."
url: https://proofline.sh/learn/postgres-query-slower-plan-change-or-more-rows/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Is the slower PostgreSQL query on a new plan, reading more rows, or waiting?

A PostgreSQL query that got ten times slower runs a different plan, runs the same plan over more rows, or spends the extra time waiting for a lock or for I/O. Compare the plans’ indexes, join order, scan conditions and estimated versus actual rows before and after, the statement's blocks per call in pg\_stat\_statements, and the session's wait\_event while the query runs. Rows returned per call often stays flat under all three, so it separates nothing.

Capacity overruns The Proofline team November 24, 2026 9 min read

## The symptom and three explanations

A fictional `ledger` service lists an account's 20 newest events with one query:

```
SELECT id, created_at FROM events WHERE account_id = $1 ORDER BY created_at DESC LIMIT 20;
```

On the night of 2026-11-18 the endpoint's p99 for account 7 went from under a millisecond to more than 100 ms. No release went out. Three explanations fit:

-   The plan changed. Fresh statistics, a dropped or new index, or a different parameter type led the planner to another plan.
-   The plan is the same and it reads more rows. Account 7 imported its history, so the same index scan now visits far more rows.
-   The query waits. A migration holds a lock on the table, or reads from disk are slow.

All three predict the latency graph, and each is common. [Choose the observation where explanations disagree](/learn/which-observation-separates-two-explanations/)

## Where the predictions differ

| Observation | Plan changed | Same plan, more rows | Waiting |
| --- | --- | --- | --- |
| Mean execution time in `pg_stat_statements` | rises | rises | rises for row locks and I/O; a lock taken before execution is not in it |
| Rows returned per call | flat | flat under `LIMIT`, rises without it | flat |
| Blocks read or hit per call | usually rises | rises | flat |
| Access paths and join order | at least one plan detail changes, possibly within the same node type | unchanged | can be unchanged |
| Estimated against actual rows on the scan | often far apart | apart while statistics are stale | as before |
| `wait_event_type` while it runs | none, or `IO` | none, or `IO` | `Lock`, `LWLock` or `IO` |

Two plans can both say `Index Scan` while choosing different indexes or scan conditions. Compare the full plans, then use blocks per call and wait samples to distinguish extra work from time spent waiting. `pg_stat_statements` records rows, blocks hit and read, and the mean execution time for each normalized statement. [pg\_stat\_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) `EXPLAIN ANALYZE` prints each node's estimated rows next to the rows it actually produced, and the docs call their agreement the thing usually most important to look for. Under a `LIMIT`, a node's estimate assumes it runs to completion, so compare the rows it had to read, such as `Rows Removed by Filter`, with how many it was expected to need. [Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)

## The lab: one query through four phases

The lab loads one million events into PostgreSQL 17, in which account 7 has 20 old rows, and runs the query 20 times per phase. Phase T1 imports 50,000 older events for account 7, T2 runs `ANALYZE`, as autovacuum would after that many changes, and T3 holds a table lock while the query runs. Autoanalyze runs once a table's changes exceed `autovacuum_analyze_threshold` plus 10% of the table by default; the lab turns autovacuum off to choose when. [Autovacuum settings](https://www.postgresql.org/docs/current/runtime-config-vacuum.html)

Save `setup.sql`:

```
CREATE EXTENSION pg_stat_statements;
CREATE TABLE events (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id int NOT NULL,
  created_at timestamptz NOT NULL,
  amount     numeric(10,2) NOT NULL
);
INSERT INTO events (account_id, created_at, amount)
SELECT CASE WHEN i <= 50000 AND i % 2500 = 0 THEN 7 ELSE 8 + i % 99991 END,
       timestamptz '2026-01-01' + i * interval '20 seconds',
       (i % 1000) / 10.0
FROM generate_series(1, 1000000) i;
CREATE INDEX events_account_id ON events (account_id);
CREATE INDEX events_created_at ON events (created_at);
VACUUM ANALYZE events;
```

`import.sql`:

```
INSERT INTO events (account_id, created_at, amount)
SELECT 7, timestamptz '2025-01-01' + i * interval '5 minutes', 1
FROM generate_series(1, 50000) i;
```

and `lab.sh`:

```
set -euo pipefail
psql() { docker exec -i "$lab" psql -U postgres -X -v ON_ERROR_STOP=1 "$@"; }
Q="SELECT id, created_at FROM events WHERE account_id = 7 ORDER BY created_at DESC LIMIT 20"

phase() {   # run the query 20 times, then read what pg_stat_statements and EXPLAIN say
  psql -qc "SELECT pg_stat_statements_reset()" >/dev/null
  for i in $(seq 20); do psql -qc "$Q" >/dev/null; done
  psql -At -F ' | ' -c "SELECT '$1', calls, round(mean_exec_time::numeric, 1) || ' ms',
      rows / calls || ' rows/call', (shared_blks_hit + shared_blks_read) / calls || ' blocks/call'
    FROM pg_stat_statements WHERE query LIKE 'SELECT id, created_at FROM events%'"
  psql -At -c "EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) $Q" | grep -E 'Scan|Removed' | sed 's/^/    /'
}

psql -q < setup.sql          # 1M events, account 7 has 20 old rows
phase "T0 baseline"
psql -q < import.sql         # account 7 imports 50,000 older events
phase "T1 import  "
psql -qc "ANALYZE events"    # what autovacuum would do next
phase "T2 analyze "

# Keep the transaction open until the observer has recorded the wait.
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkfifo "$work/locker"
psql -q < "$work/locker" >/dev/null &
locker=$!
exec 3>"$work/locker"
printf '%s\n' "SET application_name='plan_lab_locker'; BEGIN; LOCK TABLE events IN ACCESS EXCLUSIVE MODE;" >&3

poll() {
  for attempt in $(seq 50); do
    result=$(psql -Atqc "$1")
    if [ -n "$result" ]; then printf '%s\n' "$result"; return; fi
    sleep 0.1
  done
  echo "Timed out waiting for $2" >&2
  return 1
}
poll "SELECT 1 FROM pg_locks l JOIN pg_stat_activity a USING (pid)
      WHERE a.application_name='plan_lab_locker' AND l.relation='events'::regclass
        AND l.mode='AccessExclusiveLock' AND l.granted" 'table lock' >/dev/null
psql -qc "SELECT pg_stat_statements_reset()" >/dev/null
psql -c '\timing on' -c "SET application_name='plan_lab_reader'" -c "$Q" > "$work/waited" 3>&- &
reader=$!
poll "SELECT concat_ws(' | ', 'T3 lock', wait_event_type, wait_event, state)
      FROM pg_stat_activity WHERE application_name='plan_lab_reader' AND wait_event_type='Lock'
        AND (SELECT pid FROM pg_stat_activity WHERE application_name='plan_lab_locker') = ANY(pg_blocking_pids(pid))" 'blocked reader'
printf '%s\n' 'COMMIT;' >&3
exec 3>&-
wait "$locker"
wait "$reader"
psql -At -F ' | ' -c "SELECT 'T3 lock   ', calls, round(mean_exec_time::numeric, 1) || ' ms'
  FROM pg_stat_statements WHERE query LIKE 'SELECT id, created_at FROM events%'"
grep '^Time:' "$work/waited" | tail -1 | sed 's/^/T3 client  | /'
```

Run it against a server with `pg_stat_statements` preloaded, then remove the container. It takes about 20 seconds.

```
(
  set -eu
  lab=$(docker run -d -e POSTGRES_PASSWORD=lab postgres:17 \
    -c shared_preload_libraries=pg_stat_statements -c autovacuum=off)
  export lab
  trap 'docker rm -f "$lab" >/dev/null' EXIT
  attempts=0
  until docker exec "$lab" pg_isready -q -h 127.0.0.1; do
    attempts=$((attempts + 1))
    if [ "$attempts" -ge 30 ] || [ "$(docker inspect -f '{{.State.Running}}' "$lab")" != true ]; then
      docker logs "$lab" >&2
      exit 1
    fi
    sleep 1
  done
  bash lab.sh
)
```

Write the prediction down first: T1 keeps the bitmap scan on `events_account_id` with far more actual rows, T2 changes the scan node, rows per call stays at 20 throughout, and T3 shows a `Lock` wait before execution begins. PostgreSQL 17.12 printed:

```
T0 baseline | 20 | 0.3 ms | 20 rows/call | 26 blocks/call
            ->  Bitmap Heap Scan on events  (cost=4.50..43.52 rows=10 width=16) (actual rows=20 loops=1)
                  ->  Bitmap Index Scan on events_account_id  (cost=0.00..4.50 rows=10 width=0) (actual rows=20 loops=1)
T1 import   | 20 | 14.9 ms | 20 rows/call | 434 blocks/call
            ->  Bitmap Heap Scan on events  (cost=4.51..47.40 rows=11 width=16) (actual rows=50020 loops=1)
                  ->  Bitmap Index Scan on events_account_id  (cost=0.00..4.51 rows=11 width=0) (actual rows=50020 loops=1)
T2 analyze  | 20 | 202.2 ms | 20 rows/call | 12790 blocks/call
      ->  Index Scan Backward using events_created_at on events  (cost=0.43..48773.23 rows=49000 width=16) (actual rows=20 loops=1)
            Rows Removed by Filter: 997481
T3 lock | Lock | relation | active
T3 lock    | 1 | 192.9 ms
T3 client  | Time: 209.460 ms
```

T0 to T1 is the same plan reading more rows: the same two nodes, an estimate of 11 rows against 50,020 actual, and 17 times the blocks. T1 to T2 is a plan change with the same data. With fresh statistics the planner expected account 7's rows among the newest, walked the `created_at` index backwards and discarded 997,481 rows to find 20, because account 7's rows are all old. T1 ran about 50 times slower than T0 and T2 about 14 times slower than T1, and rows per call never moved. Your timings will differ; the node types and row counts will not, apart from the estimate on the T2 scan, which comes from a random sample. [ANALYZE](https://www.postgresql.org/docs/current/sql-analyze.html)

T3 is the trap. The observer saw the reader blocked by the session holding the table lock. The client measured 209.460 ms and `pg_stat_statements` recorded 192.9 ms of execution. The table lock wait happens before execution starts. The difference includes client overhead as well as the wait. In a separate run, a `SELECT ... FOR UPDATE` that waited 1.8 seconds on another session's row lock recorded 1,828 ms, since that wait happens during execution. A changed access path in T1 or unchanged access paths in T2 would have falsified the prediction. Change `50000` in `import.sql` to `5000`: T1 is then only about five times slower than T0, and T2 flips to the same backward scan.

## Read it on a real system

Read the statement's history from `pg_stat_statements`, as two snapshots some minutes apart or from your monitoring, since its counters are cumulative from `stats_since`. With `track_io_timing` on, `shared_blk_read_time` (PostgreSQL 17 and later) shows time spent reading blocks, the I/O wait. [pg\_stat\_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) · [track\_io\_timing](https://www.postgresql.org/docs/current/runtime-config-statistics.html)

```
SELECT queryid, calls, round(mean_exec_time::numeric, 2) AS mean_ms,
       rows / calls AS rows_per_call,
       (shared_blks_hit + shared_blks_read) / calls AS blocks_per_call,
       round((shared_blk_read_time / calls)::numeric, 2) AS read_ms_per_call, stats_since
FROM pg_stat_statements
WHERE query LIKE '%FROM events WHERE account_id%' AND calls > 0
ORDER BY total_exec_time DESC LIMIT 5;
```

Check when the table was last analyzed and how much changed since:

```
SELECT last_analyze, last_autoanalyze, n_mod_since_analyze, n_live_tup
FROM pg_stat_user_tables WHERE relname = 'events';
```

While a slow call runs, sample its wait and who blocks it. `wait_event_type` is `Lock` for a heavyweight lock and `IO` for an I/O wait. [pg\_stat\_activity](https://www.postgresql.org/docs/current/monitoring-stats.html) · [pg\_blocking\_pids](https://www.postgresql.org/docs/current/functions-info.html)

```
SELECT pid, wait_event_type, wait_event, state, now() - query_start AS running,
       pg_blocking_pids(pid) AS blocked_by, left(query, 60)
FROM pg_stat_activity WHERE query LIKE '%FROM events WHERE account_id%' AND pid <> pg_backend_pid();
```

For the current estimated plan, use plain `EXPLAIN` with the slow call's parameter types and values. It shows the chosen index, scan conditions and estimated rows without executing the statement. [EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html)

```
EXPLAIN
SELECT id, created_at FROM events WHERE account_id = 7 ORDER BY created_at DESC LIMIT 20;
```

For actual rows or buffer counts, read a plan already captured during the incident or reproduce the query with fixtures in a disposable database. `EXPLAIN ANALYZE` runs the statement. Even a `SELECT` can call a function that modifies data. A sequence value taken by `nextval` stays consumed after rollback. [Function volatility](https://www.postgresql.org/docs/current/xfunc-volatility.html) · [Sequence functions](https://www.postgresql.org/docs/current/functions-sequence.html)

To keep the plan the query had during the incident, rather than the one it has when you look, load `auto_explain` with `auto_explain.log_min_duration` set. That is a configuration change. [auto\_explain](https://www.postgresql.org/docs/current/auto-explain.html)

## Limits

`pg_stat_statements` keeps one row per normalized statement. Every parameter value and every plan of that statement lands in the same mean, so one skewed account can be slow while the mean barely moves. Split by account in the application's own metrics or traces.

The plan you get from `EXPLAIN` today is not necessarily the plan the application ran. Statistics may have changed since, and a prepared statement can run a generic plan or bind a parameter of another type. [Check an index against the query the app sends](/learn/postgres-index-parameter-types/)

A client that waited for a pooled connection before its query reached the server shows a slow request and an unchanged database. Read the pool's own counts. [Pool acquire timeout: a busy pool or a struggling database?](/learn/connection-pool-timeout-or-slow-database/)

More than one explanation can hold at once. In the lab, the import made the query slower and then caused the analyze that made it slower again.

## Questions

### Why did my PostgreSQL query plan change without a deploy?

The planner chooses from statistics that `ANALYZE` refreshes, and autovacuum runs `ANALYZE` on its own once enough rows changed. New statistics can make another plan look cheaper, as in the lab's T2. `last_autoanalyze` shows when it last happened.

### Does pg\_stat\_statements include lock wait time?

It records execution time. In the lab, a wait for a row lock during execution was included, and a wait for a table lock before execution was not. A mean that stayed flat while clients saw seconds points at a wait before execution or outside the database.

### Why is rows per call unchanged when the query reads much more?

`rows` counts the rows a statement returned. A query with `LIMIT 20` returns 20 rows whether it read 20 or a million to find them. Blocks per call and `Rows Removed by Filter` show the work.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Check a new PostgreSQL index against the query the app sends](/learn/postgres-index-parameter-types/)
    
    Breaking migrations The Proofline team November 20, 2026 3 min read
    
-   ### [Pool acquire timeout: a busy pool or a struggling database?](/learn/connection-pool-timeout-or-slow-database/)
    
    Capacity overruns The Proofline team November 23, 2026 6 min read
