Practical 2 · When the planner guesses wrong
Goal: three slow queries where the planner’s row estimate is the clue: one where old statistics make it build the wrong plan, one where two related columns fool it, and one where it plans around too little memory. For each, you compare
rows=with the actual rows, give the planner what it lacks, and measure.Time: ~40 minutes. Where: psql in your
explain-dbcontainer (docker exec -it explain-db psql -U postgres -d shop), and~/pg-explain/for the lab script. Read lesson 4 first.
This practical’s ./lab setup p2 comes at the start of task 2, where it gives every customer a city: don’t run it
before task 1.
Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p2 starts you here with the earlier
practicals’ solutions in place. It takes about 1½ minutes
on a Raspberry Pi 4, most of it loading the shop.
In every task, run each EXPLAIN ANALYZE twice and work on the second run. The planner’s estimates (rows=) come
from ANALYZE, which reads a random sample of the table, so yours may differ a little from the ones below.
Task 1 · A backlog the statistics haven’t seen
The warehouse has cleared its backlog: every pending order from before 20 December 2026 is shipped. In psql:
UPDATE orders SET status = 'shipped' WHERE status = 'pending' AND created_at < '2026-12-20';
UPDATE 59395
211 orders are still pending. The packing screen lists them with the customer’s email:
SELECT o.id, o.created_at, c.email FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending';
Predict first: how many pending orders will the planner expect? Which join method suits 211 rows?
Run EXPLAIN ANALYZE on it. Find the estimate that’s wrong, the join it led to, and the line that shows the index
still knows about the old pending orders.
What the second run showed on the Raspberry Pi 4
Hash Join (cost=20335.82..28047.16 rows=60134 width=38) (actual time=490.564..601.797 rows=211.00 loops=1)
-> Seq Scan on customers c (cost=0.00..3860.00 rows=200000 width=30) (actual time=0.039..46.701 rows=200000.00 loops=1)
-> Hash (cost=19584.14..19584.14 rows=60134 width=24) (actual time=487.683..487.688 rows=211.00 loops=1)
-> Bitmap Heap Scan on orders o (cost=1670.47..19584.14 rows=60134 width=24) (actual time=487.361..487.537 rows=211.00 loops=1)
Heap Blocks: exact=16187
-> Bitmap Index Scan on orders_status_created_at_idx (cost=0.00..1655.43 rows=60134 width=0) (actual time=30.465..30.466 rows=59606.00 loops=1)
...
Execution Time: 602.690 ms
| Line | Says |
|---|---|
rows=60134 against rows=211.00 | the planner still thinks about 3% of orders are pending: the statistics are from before the UPDATE |
Hash Join over all 200,000 customers | the method for tens of thousands of rows |
Bitmap Index Scan ... rows=59606.00 | the index still lists the old versions of the shipped orders; the scan visits 16,187 pages to check them and keeps 211 rows |
Why hasn’t autovacuum caught up? Ask Postgres:
SELECT n_mod_since_analyze, last_autoanalyze FROM pg_stat_user_tables WHERE relname = 'orders';
59395 |
59,395 rows changed, and no automatic ANALYZE yet. Autovacuum analyzes a table once 50 rows + 10% of it have
changed, 200,050 here, and vacuums it after 50 + 20% (autovacuum_analyze_scale_factor, autovacuum_vacuum_scale_factor
in Vacuuming). A change to 3% of a
table can change a query’s answer completely and leave the statistics as they were.
An UPDATE doesn’t change a row in place: it writes a new version and leaves the old one, still listed in the index,
until VACUUM removes it (Routine Vacuuming).
Requirement: make the planner see the table as it is now, with one command that refreshes the statistics and removes the old row versions; then run the query twice again.
Solution and what it showed
VACUUM ANALYZE orders;
Nested Loop (cost=0.85..4755.85 rows=533 width=38) (actual time=0.113..2.186 rows=211.00 loops=1)
-> Index Scan using orders_status_created_at_idx on orders o (cost=0.43..1214.66 rows=533 width=24) (actual time=0.088..0.311 rows=211.00 loops=1)
-> Index Scan using customers_pkey on customers c (cost=0.42..6.64 rows=1 width=30) (actual time=0.007..0.007 rows=1.00 loops=211)
...
Execution Time: 2.272 ms
2.3 ms instead of 603 ms. ANALYZE took a new sample: 8 of its 30,000 rows were pending, and 8/30,000 of
2,000,000 is the rows=533 (other walk-throughs got 200 and 333: 3 or 5 pending rows in the sample). Not 211, but the right size, and the planner chose a Nested Loop with 211 lookups. VACUUM
removed the old versions, so the index finds only the 211 live rows.
Task 2 · Two columns that go together
The marketing team wants revenue from customers in Berlin. Customers need a city first. In ~/pg-explain (\q
first, or a second terminal):
./lab setup p2
giving every customer a city with sql/cities.sql (a few seconds)…
✓ every customer has a city: 8,333 in Berlin (6 s)
ready for p2. psql in the container: docker exec -it explain-db psql -U postgres -d shop
(every command is in lab.log; ./lab setup p2 -v shows them as they run)
Every country gets 3 cities, and cities.sql ends with VACUUM ANALYZE customers: the estimate below isn’t stale.
What setup did
It ran ~/pg-explain/sql/cities.sql (read it): a city column on customers, filled for all 200,000. Run again,
it keeps your cities.
The query:
SELECT count(*), sum(o.total_cents) FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'DE' AND c.city = 'Berlin';
Predict first: an eighth of customers are in
DE, a twenty-fourth inBerlin. Multiplying them as lesson 4 says, how many Berlin customers will the planner expect?
Run EXPLAIN ANALYZE, and find the scan of customers.
What it showed
-> Parallel Seq Scan on customers c (cost=0.00..5224.00 rows=440 width=8) (actual time=15.562..53.405 rows=2777.67 loops=3)
Filter: ((country = 'DE'::text) AND (city = 'Berlin'::text))
440 per process (about 1,056 in all) against 2,777.67 × 3 = 8,333: 1/8 × 1/24 of 200,000 is 1,042. The planner
doesn’t know that every Berlin customer is in DE. A Nested Loop with 8,333 lookups into orders took 402 ms.
CREATE STATISTICS can also record how far one column determines another (the kind dependencies): statistics on
several columns together, called extended statistics.
Requirements:
- create extended statistics named
customers_country_city_stats, of the kinddependencies, oncountryandcityofcustomers(CREATE STATISTICS) - run the query with
EXPLAIN ANALYZEstraight away, before anything else - then make the statistics count, and run it twice more
Solution
CREATE STATISTICS customers_country_city_stats (dependencies) ON country, city FROM customers;
ANALYZE customers;
Break it, built in: straight after CREATE STATISTICS, the scan still said rows=440, as lesson 4 said it would.
After ANALYZE customers:
-> Parallel Hash Join (cost=5266.36..32949.24 rows=33888 width=4) (actual time=23.553..443.468 rows=27784.67 loops=3)
...
-> Parallel Seq Scan on customers c (cost=0.00..5224.00 rows=3389 width=8) (actual time=0.962..21.190 rows=2777.67 loops=3)
...
Execution Time: 477.105 ms
rows=3389 per process: about 8,133, right. And it was slower. With the right count, the planner priced the
Nested Loop at 41,254 and chose a Hash Join priced at 34,119, which took 477–518 ms against the Nested Loop’s
392–402 ms. The planner’s costs are estimates too. A wrong estimate matters when it changes the plan for the worse,
as in Task 1; the time tells you whether a fix helped.
Task 3 · A report planned around too little memory
The monthly report of the 10 best customers:
SELECT customer_id, sum(total_cents) AS spent FROM orders GROUP BY customer_id ORDER BY spent DESC LIMIT 10;
Run EXPLAIN ANALYZE. Which node takes the time, and how does it get the orders grouped by customer?
What it showed
-> GroupAggregate (cost=0.43..119505.99 rows=178819 width=16) (actual time=0.175..7066.305 rows=199990.00 loops=1)
Buffers: shared hit=1899819 read=101888
-> Index Scan using orders_customer_id_idx on orders (cost=0.43..107717.80 rows=2000000 width=12) (actual time=0.131..6201.012 rows=2000000.00 loops=1)
...
Execution Time: 7208.069 ms
7.2 s. To group, the plan reads all 2,000,000 orders through the customer_id index, so they come out customer by
customer: 6.2 s of it in the Index Scan, 2,001,707 pages touched for a table of 17,162 (the Seq Scan below reads
all of them). The table was 16,667 pages: task 1’s UPDATE wrote new versions of 59,395 rows, about 495 pages at
~120 rows a page, and VACUUM frees the old versions’ space for reuse but keeps the pages.
Predict first: a hash table of 178,819 customers’ sums needs more than 4 MB × 2. What will the plan be with
SET work_mem = '64MB';?
Set it for your session, then run the query twice.
-> HashAggregate (cost=47162.00..48950.19 rows=178819 width=16) (actual time=2169.001..2287.515 rows=199990.00 loops=1)
Batches: 1 Memory Usage: 12313kB
-> Seq Scan on orders (cost=0.00..37162.00 rows=2000000 width=12) (actual time=0.039..431.267 rows=2000000.00 loops=1)
...
Execution Time: 2359.256 ms
2.3 s: one Seq Scan and a hash table of 12,313 kB, more than the 8 MB a hash could have at 4 MB.
Was memory what it lacked? In a new session, at 4 MB, with the index plan and parallel workers switched off for
the test (SET enable_indexscan = off; SET max_parallel_workers_per_gather = 0;), the hash spilled to disk:
Planned Partitions: 4 Batches: 5 Memory Usage: 8249kB Disk Usage: 31744kB
...
Execution Time: 3321.699 ms
The spill cost about 1 second (3.3 s against 2.3 s); the planner’s choice cost about 4 more (7.2 s). It priced
the spilling hash at 190,471 and reading 2,000,000 rows through the index at 123,370, then took the cheaper-looking
one. At 64 MB the hash plan was priced at 52,814, below the index plan, so the planner chose it. Raising work_mem is the fix here because it changes the prices.
Break it: leave psql (\q) and connect again. Run SHOW work_mem; and EXPLAIN on the query: 4MB, and the
GroupAggregate is back. SET lasts for one session. For a report, set it in the report’s own session (or
ALTER ROLE reports SET work_mem = '64MB'; for a role only reports use), not for the whole server: lesson 4’s
19,200 MB is what a server-wide 64 MB can add up to.
Check your work
./lab check p2
All 13 checks should pass: 211 pending orders, fresh statistics, no old row versions left and a Nested Loop for the
packing screen, the cities
and their extended statistics, and work_mem still 4 MB for everyone.
Next: lesson 5 · In production.