5 · In production
In one sentence: on a running database you first find the query that costs the most time in total (
pg_stat_statements), take real values for it from the slow-query log, then read its plan twice and compare like with like: the cache, the plan a prepared statement uses, and whatEXPLAIN ANALYZEchanges all differ from a quiet test.
The problem
So far the lessons gave you the slow query. In a running app, thousands of queries go by each minute and someone says “the shop is slow”. To find the one worth fixing, Postgres has to keep score.
Which queries take the time: pg_stat_statements
pg_stat_statements is an extension that ships with Postgres. It is loaded when the server starts
(shared_preload_libraries) and then counts every statement
(pg_stat_statements). Practical 3 sets it up.
Here pgbench, a load tool that ships with Postgres, played an app for 30 seconds: 4 connections
running three queries over and over: a My orders page, Practical 2’s packing screen and lesson 2’s revenue report.
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 1) AS mean_ms,
left(query, 50) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
calls | total_ms | mean_ms | query
-------+----------+---------+----------------------------------------------------
249 | 73801 | 296.4 | SELECT c.country, count(*) AS orders, sum(o.total_
12457 | 21848 | 1.8 | SELECT id, status, total_cents, created_at FROM or
1086 | 5377 | 5.0 | SELECT o.id, o.created_at, c.email FROM orders o J
| Column | Means |
|---|---|
calls | how many times it ran |
total_exec_time | milliseconds spent running it, all calls together |
mean_exec_time | the average per call |
Sort by total time: it is where the server’s time goes. The revenue report is first. My orders is second at 1.8 ms a call, because it ran 12,457 times.
Each line stands for one query shape: constants become $1, $2. The revenue report is stored as
WHERE o.created_at >= $1 AND o.created_at < $2. To run EXPLAIN you need real values.
Real values: the slow-query log
log_min_duration_statement logs every statement that took longer than the setting, as it was sent
(Error Reporting and Logging). With 250ms,
in docker logs:
2026-11-24 16:26:39.639 UTC [1079] LOG: duration: 314.983 ms statement: SELECT c.country, count(*) AS orders, sum(o.total_cents) AS revenue_cents
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= '2026-10-01' AND o.created_at < '2026-11-01'
Paste that statement after EXPLAIN (ANALYZE, BUFFERS).
The plan as it ran: auto_explain
You run EXPLAIN later, on a quieter server. auto_explain logs the plan of the slow run itself, at the moment it
was slow (auto_explain). For every new connection:
ALTER SYSTEM SET session_preload_libraries = 'auto_explain';
ALTER SYSTEM SET auto_explain.log_min_duration = '250ms';
ALTER SYSTEM SET auto_explain.log_analyze = on;
ALTER SYSTEM SET auto_explain.log_buffers = on;
SELECT pg_reload_conf();
2026-11-24 16:27:07.861 UTC [1257] LOG: duration: 257.056 ms plan:
Query Text: SELECT c.country, count(*) AS orders, sum(o.total_cents) AS revenue_cents
...
Sort (cost=26326.06..26326.08 rows=8 width=19) (actual time=247.870..257.024 rows=8.00 loops=1)
log_analyze measures every statement, not only the slow ones; the documentation warns that this can slow a busy
server a lot. Turn it on to catch a problem, then off (before Practical 3, whose numbers were measured without it):
ALTER SYSTEM RESET session_preload_libraries;
ALTER SYSTEM RESET auto_explain.log_min_duration;
ALTER SYSTEM RESET auto_explain.log_analyze;
ALTER SYSTEM RESET auto_explain.log_buffers;
SELECT pg_reload_conf();
Measure like with like: the cache
Lesson 1 said to run twice. Two queries, each run twice right after a server restart (Postgres’s cache empty): My
orders for customer 4242, a few pages, and the sum of all total_cents, all 17,162 pages of orders. In some rounds
the operating system’s cache of the database files was emptied too, so the first run read from the USB SSD.
SET track_io_timing = on; adds the time spent waiting for reads. Three rounds each:
| Run | customer 4242 | sum of all orders |
|---|---|---|
| first, pages from the SSD | 3.0–3.3 ms | 568–586 ms |
| first, pages from the operating system’s cache | 0.82–0.85 ms | 307–345 ms |
| second | 0.13–0.15 ms | 310–353 ms |
Buffers: shared hit=7 read=17155
I/O Timings: shared read=539.696
That was the full scan from the SSD: 540 ms waiting for reads, for the three processes together. From the operating
system’s cache, the same read=17155 waited 14–24 ms. read= means “not in Postgres’s cache”, not “from disk”:
I/O Timings tells you which.
Customer 4242’s second run found every page in Postgres’s cache (hit= only). The
full scan’s second run read all its pages again from the operating system’s cache: a table this big doesn’t stay in
Postgres’s 128 MB cache.
Prepared statements: one plan for every value
Some database libraries prepare a query once, then run it with different values. After five runs Postgres may switch to a generic plan, made without looking at the value (the plans before it are custom plans, made for the value given) (PREPARE):
PREPARE by_status(text) AS SELECT count(*), sum(total_cents) FROM orders WHERE status = $1;
After five EXECUTE by_status('delivered');, the next runs, for the 211 pending orders:
-> Parallel Seq Scan on orders (cost=0.00..27578.67 rows=208333 width=4) (actual time=190.239..195.110 rows=70.33 loops=3)
Filter: (status = $1)
...
Execution Time: 213.498 ms
$1 in a plan means a generic plan: built for a quarter of the table (4 values; 208,333 per process × 2.4 = 500,000 rows), whatever you asked. With
SET plan_cache_mode = force_custom_plan; the same EXECUTE used the index: 0.38–0.41 ms instead of 213–220 ms.
A checklist
1 find pg_stat_statements, by total_exec_time (and by mean for one slow page)
2 values the slow-query log: the statement as it was sent
3 read EXPLAIN (ANALYZE, BUFFERS), twice; BEGIN ... ROLLBACK around writes
4 where the node with the most time of its own (lesson 2)
5 why the condition and the index (lesson 3); rows= against actual rows (lesson 4)
6 fix one change; then measure again, the same way, warm against warm
Try it on your computer
Practical 3 · Capstone: slow-query hunt: an app you’re given runs against your database; you find its slowest queries, fix them and write down the numbers.
Go deeper: when the generic plan wins
For its first five runs a prepared statement gets a custom plan, made for the values given. From then on Postgres
compares the generic plan’s estimated cost with the average cost of the custom plans so far, and takes the generic
one unless it costs clearly more (PREPARE, Notes). Five
'delivered' runs were priced at 32,327 each, the generic plan at 29,621, so the sixth run used the generic plan.
One cheap run among the five is enough. In another session one of them was for 'pending' (an Index Scan, cost 1,217): the
average of the five was 26,105, below the generic plan’s cost, and all eight runs got custom plans
(generic_plans 0, custom_plans 8 in pg_prepared_statements). Which plan a prepared statement uses depends on the
values it has seen.
Common misunderstandings
- “The plan
EXPLAINshows me is the plan the app ran.” The app’s run may have used a generic plan, had a colder cache or shared a busy server. The planauto_explainlogged is the one that ran.
Check yourself
1. pg_stat_statements shows a query with calls 900000, mean_ms 0.4, and another with calls 12, mean_ms 3000. Which costs the server more?
The first: 900,000 × 0.4 = 360,000 ms, against 12 × 3,000 = 36,000 ms. The second may still be worth fixing for the
person who waits 3 seconds, but it isn't where the server's time goes.
2. A plan from your app's log shows Filter: (customer_id = $1) and a Seq Scan, but your EXPLAIN ANALYZE with a real value shows an Index Scan. Why?
$1 means the app's run used a generic plan, made without the value. Your EXPLAIN with a
literal got a custom plan. Reproduce it with PREPARE and six EXECUTEs, or try
plan_cache_mode = force_custom_plan for that app's connections.
3. A query took 2.1 s in the log, but 90 ms when you ran EXPLAIN (ANALYZE, BUFFERS). Name two things to compare.
The cache: your run may find in memory pages the app's run had to read (read=, and I/O Timings
with track_io_timing). And the plan: compare yours with the one auto_explain logged; it may
be a generic plan, or the server may have been busy then.