Sub topic 8
Taking a Suspect Query to EXPLAIN (ANALYZE, BUFFERS)
pg_stat_statements tells you which queries cost the most. It does not tell you why. This chapter covers the handoff: turning a row from the statistics view into a plan you can read and act on.
This chapter assumes you can read the rankings from the earlier chapters (total_exec_time, mean_exec_time, calls, shared_blks_read) and that you know what a query plan is. You need a role that can run queries against the target database, ideally a staging copy.
From a statistics row to a runnable query
A row in pg_stat_statements holds normalized text. Constants are replaced by placeholders, so you will see something like this:
SELECT * FROM orders WHERE customer_id = $1You cannot paste that into EXPLAIN ANALYZE, because there is no value for $1. You also should not guess a value. The planner uses column statistics to estimate how many rows match, so the plan for a rare value can differ from the plan for a common one. A plan you capture with an unrepresentative value may not be the plan that makes the query slow.
You can find real values in several places:
- The application's own logs or ORM debug output.
- The server log, if
log_min_duration_statementis set. Slow statements are logged with their parameters. pg_stat_activity.query, for statements running right now (it shows the text the client sent, which may still contain$1for prepared statements).- The
auto_explainmodule, which logs plans of slow statements as they run. - A teammate who knows which customers, dates, or tenants are typical and which are extreme.
Try at least two values: a typical one and the largest or most unusual one you can find. Slow means in mean_exec_time often come from the unusual values.
Running EXPLAIN (ANALYZE, BUFFERS)
Plain EXPLAIN shows the plan the planner chose and its estimates. EXPLAIN ANALYZE also executes the query and reports what actually happened. Adding BUFFERS reports how many 8 kB blocks each plan node touched. That connects the plan to the buffer columns you already read in pg_stat_statements.
The following script creates a table that resembles the suspect query's target, so you can follow along:
CREATE TABLE orders AS
SELECT i AS id,
(i % 100000) + 1 AS customer_id,
now() - (i || ' seconds')::interval AS created_at,
md5(i::text) AS note
FROM generate_series(1, 1000000) AS i;
ANALYZE orders;
SET max_parallel_workers_per_gather = 0; -- keeps the plan simple for this example
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;The output looks like this. Your costs, timings, and block counts will differ.
Seq Scan on orders (cost=0.00..21925.00 rows=10 width=57) (actual time=0.040..96.512 rows=10 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 999990
Buffers: shared hit=1500 read=8425
Planning Time: 0.110 ms
Execution Time: 96.560 msReading the plan against the statistics
Work through the output in this order.
- Node type and filter.
Seq ScanwithRows Removed by Filter: 999990means the query read a million rows to return ten. That is the core problem. - Estimated versus actual rows. The estimate
rows=10matches the actualrows=10, so the planner's statistics are fine here. A large gap between the two (for example an estimate of 10 and an actual of 500000) points to stale statistics, correlated columns, or a skewed value. In that case runANALYZEon the table or consider extended statistics. - Loops.
actual timeandrowsare per loop. A node withloops=5000andactual time=0.02..0.03costs about 5000 × 0.03 ms in total. Multiply before you compare nodes. - Buffers.
shared hit=1500 read=8425means the node touched 9925 blocks. 1500 were found in shared buffers and 8425 were not. Those 8425 reads were satisfied by the operating system cache or by the disk. The plan cannot tell you which. - Planning and execution time.
pg_stat_statementsrecords execution time intotal_exec_timeand planning time separately intotal_plan_time(only whenpg_stat_statements.track_planningis on). CompareExecution Timewith themean_exec_timeyou saw earlier. If they are similar, you have reproduced the problem. If your run is far faster, your parameter values or cache state differ from production.
| What you saw in pg_stat_statements | What to look for in the plan |
|---|---|
| High `mean_exec_time`, low `calls` | One expensive node: a large scan, a sort, a join with a bad estimate |
| Low `mean_exec_time`, very high `calls` | A cheap plan that is fine per call. Look at the application for repeated calls instead |
| High `shared_blks_read`, low `hit_pct` | Large `read=` counts on scan nodes, often a missing index or a table bigger than the cache |
| High `temp_blks_written` | `Sort Method: external merge Disk: ...` or `Batches` greater than 1 on a hash node |
| Large gap between `min_exec_time` and `max_exec_time` | Different plans or cache state per parameter value. Test several values |
Fixing and confirming
The plan above suggests an index on customer_id. On a live system, build it without blocking writes:
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;Index Scan using orders_customer_id_idx on orders (cost=0.42..43.80 rows=10 width=57) (actual time=0.045..0.071 rows=10 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=13
Planning Time: 0.150 ms
Execution Time: 0.095 msThe block count dropped from about 9900 to 13, and execution time dropped from about 96 ms to under 1 ms. To confirm the improvement in production, use the windowing technique from the reset chapter: reset the statistics, let normal traffic run, and compare the query's new mean_exec_time with the old value. The queryid stays the same, because the query text did not change.
The workflow
Pitfalls and edge cases
EXPLAIN ANALYZEruns the statement. ForUPDATE,DELETE, orINSERT, the changes really happen. Wrap the statement in a transaction and roll it back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET note = 'checked' WHERE customer_id = 42;
ROLLBACK;The rollback undoes the data changes, but the work still happened. It takes locks and generates WAL while it runs, so do not do this on a busy production primary without thinking it through.
- Cache state changes the numbers. The first run after a restart often shows large
read=counts. Run the statement twice. If the second run is much faster and shows mostlyhit=, the query is slow mainly when its data is cold. Thehit_pctcolumn frompg_stat_statementstells you how common that is in real traffic. - Timing overhead.
ANALYZEreads the clock at every node. On plans with many loops this can inflate times noticeably. UseTIMING OFFif you mostly care about row counts and buffers. - Prepared statements and generic plans. An application using prepared statements may run a generic plan that ignores specific values, while your manual test gets a custom plan. On PostgreSQL 16 and later,
EXPLAIN (GENERIC_PLAN) SELECT * FROM orders WHERE customer_id = $1;shows the generic plan for a query that still has placeholders. It cannot be combined withANALYZE. - Different data, different plan. A staging database with a tenth of the rows can pick a different plan. If you must test on production data, use a restored copy or a read replica, and note that a replica has its own cache contents.
- Statistics are not a history.
pg_stat_statementsstores totals, not individual executions. If a query was slow once at 3 a.m., the view will not tell you which parameters were used. Uselog_min_duration_statementorauto_explainfor that.
Exercise
A row in pgstatstatements shows meanexectime of 850 ms for the normalized query SELECT * FROM events WHERE account_id = $1 AND created_at > $2. You run EXPLAIN (ANALYZE, BUFFERS) with a typical account and it finishes in 3 ms. What should you check next, and why?
Show answer
The slow mean likely comes from other parameter values or from cache state. Look for real values with large result sets (for example big accounts or old dates), using the logs, and compare minexectime and maxexectime in pgstatstatements for a wide gap. Re-run with those values, and compare hit and read buffer counts between a cold and a warm run. Also check whether the application uses prepared statements that run a generic plan.
Exercise
In a plan, an inner node shows actual time=0.020..0.030 rows=1 loops=20000 and Buffers: shared hit=60000. Roughly how much time does that node contribute, and what does it suggest?
Show answer
About 20000 × 0.030 ms, or up to roughly 600 ms in total, because the reported times are per loop. The 60000 buffer hits across 20000 loops suggest a nested loop repeating an index lookup for each outer row. Check whether the outer row count was underestimated, which would make the planner prefer a nested loop over a hash or merge join.