Practical 3 · Capstone: slow-query hunt
Goal: an app you’re given runs against your shop. Nobody tells you which query is slow: you make Postgres keep score, find the queries that cost the most, take them from the log, read their plans, fix them, and prove it with numbers in a report you write.
Time: ~60 minutes. Where: your terminal in
~/pg-explain/and psql inexplain-db(docker exec -it explain-db psql -U postgres -d shop). Read lesson 5 first.
./lab setup p3
✓ the app's 3 query files in sql/app/
ready for p3. psql in the container: docker exec -it explain-db psql -U postgres -d shop
(every command is in lab.log; ./lab setup p3 -v shows them as they run)
What setup did
It downloaded login.sql, my-orders.sql and daily-report.sql into ~/pg-explain/sql/app/: the app you run in
task 2. Your container and data stay as they are. Run it again and it keeps any of those files you already have,
changes included (task 4 has you edit them); delete one first for a fresh copy.
Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p3 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.
Task 1 · Let Postgres keep score
Predict first: in psql, run
CREATE EXTENSION pg_stat_statements;and thenSELECT count(*) FROM pg_stat_statements;. Will the count work?
CREATE EXTENSION
ERROR: pg_stat_statements must be loaded via "shared_preload_libraries"
The extension’s tables exist, but nothing counts until the library is loaded when the server starts. Requirements:
- the extension created in
shop(the Predict first did it) pg_stat_statementsinshared_preload_libraries, set so that it survives a restart, then the container restarted;SELECT count(*) FROM pg_stat_statements;answers- every statement that takes longer than 250 ms written to the server log (no restart needed for this one)
Hint
ALTER SYSTEM SET name = 'value'; writes a setting to a file in the data directory, so it lives in your volume.
shared_preload_libraries is read only at start: docker restart explain-db. The logging setting is
log_min_duration_statement (lesson 5), and SELECT pg_reload_conf(); makes the server read it again.
Solution
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';
\q, then docker restart explain-db, connect again, and:
SELECT count(*) FROM pg_stat_statements;
ALTER SYSTEM SET log_min_duration_statement = '250ms';
SELECT pg_reload_conf();
Task 2 · Run the app
The app is three queries, each in a file in the format of pgbench, the load tool that ships with Postgres.
./lab setup p3 put them in ~/pg-explain/sql/app/. Read them: each has a comment saying what it is, a \set line that picks a random value, and the query that uses it.
Then run the app for a minute:
docker exec explain-db pgbench -U postgres -n -c 4 -T 60 \
-f /sql/app/login.sql@60 -f /sql/app/my-orders.sql@38 -f /sql/app/daily-report.sql@2 shop
| Piece | Why |
|---|---|
-n | don’t vacuum pgbench’s own tables first: there are none in shop |
-c 4 -T 60 | 4 connections, each sending its next query as soon as the last one finishes, for 60 seconds |
-f file@60 | run this file in 60% of the runs: logins are the most frequent |
number of transactions actually processed: 963
tps = 15.982914 (without initial connection time)
A pgbench “transaction” here is one run of one file: one query. 963 in a minute, 16 a second, over 4 connections.
Predict first: which of the three takes the most time in total? Which has the highest mean?
In psql, list the top 5 by total time, then by mean, with lesson 5’s query.
What it showed
calls | total_ms | mean_ms | query
-------+----------+---------+----------------------------------------------------
568 | 218591 | 384.8 | SELECT id, country FROM customers WHERE lower(emai
17 | 18682 | 1098.9 | SELECT status, count(*), sum(total_cents) FROM ord
378 | 1404 | 3.7 | SELECT id, status, total_cents, created_at FROM or
The login takes the most time in total, the daily report the most per call (1.1 s, but only 17 calls). My orders is fast.
Create ~/pg-explain/report.md and write the “before” numbers in it: the runs per second, then one section per
file, headed by its name (login.sql, daily-report.sql, my-orders.sql), with its calls and mean.
Task 3 · Find out why
Take each slow query from the log, as you would from a real app’s. Do it before your own EXPLAINs: anything over
250 ms is logged, yours too.
docker logs explain-db 2>&1 | grep duration | grep 'lower(email)' | tail -1
docker logs explain-db 2>&1 | grep duration | grep 'created_at::date' | tail -1
2026-11-24 16:38:43.411 UTC [58] LOG: duration: 349.296 ms statement: SELECT id, country FROM customers WHERE lower(email) = lower('User' || 22756 || '@Example.com');
2026-11-24 16:38:37.646 UTC [58] LOG: duration: 1099.316 ms statement: SELECT status, count(*), sum(total_cents) FROM orders WHERE created_at::date = date '2026-11-30' - 19 GROUP BY status;
Your values and times will differ. Run each statement twice in psql with EXPLAIN (ANALYZE, BUFFERS). For each, write
in your report: the node with the most time of its own, the condition on it, and why no index serves that condition
(lesson 3).
What it showed
-> Parallel Seq Scan on customers (cost=0.00..5224.00 rows=417 width=11) (actual time=72.957..103.361 rows=0.33 loops=3)
Filter: (lower(email) = 'user22756@example.com'::text)
Rows Removed by Filter: 66666
...
Execution Time: 118.578 ms
-> Parallel Seq Scan on orders (cost=0.00..29662.00 rows=4167 width=13) (actual time=371.531..393.528 rows=612.67 loops=3)
Filter: ((created_at)::date = '2026-11-11'::date)
Rows Removed by Filter: 666054
...
Execution Time: 414.293 ms
Both read a whole table to keep a few rows, because the condition is on an expression, lower(email) and
created_at::date, and no index stores either. The planner had already worked out lower('User' || 22756 ...)
once: the Filter shows its result.
The daily report took 1,099 ms in the log and 414 ms here. In the app it ran alongside three other connections, most of them running the login’s full scan. The same slowed My orders: its query and index don’t change in task 4, yet its mean falls from 3.7 ms to 0.9 ms once the scans are gone (task 4’s list).
Task 4 · Fix them, and prove it
Requirements:
- the login must not change: the app’s code can’t be released today. Make
login.sqlfast as it is - the daily report: you may change
daily-report.sql, as long as it gives the same answer
Break it first: for the daily report, try an index on its expression:
CREATE INDEX ON orders ((created_at::date));
ERROR: functions in index expression must be marked IMMUTABLE
An index stores the expression’s value once; the expression must give the same result every time. This one doesn’t:
SELECT id, created_at, created_at::date FROM orders WHERE id = 1920715;
SET TimeZone = 'Asia/Tokyo';
SELECT id, created_at, created_at::date FROM orders WHERE id = 1920715;
1920715 | 2026-11-10 20:00:05+00 | 2026-11-10
...
1920715 | 2026-11-11 05:00:05+09 | 2026-11-11
The same order belongs to 10 November in UTC and to 11 November in Tokyo. RESET TimeZone; afterwards.
Hint
The login: lesson 3’s Check yourself 1 has the same condition. The daily report: rewrite the condition on
created_at itself, which an index already covers. “created_at::date is that day” means “created_at is from that day’s midnight up to, not including, the next
day’s”. date '2026-11-30' - :d is a date; + 1 is the next day. Run the old and the new query for one day
(replace :d with 23) and compare their rows.
Solution
CREATE INDEX customers_lower_email_idx ON customers (lower(email));
The query line of daily-report.sql, rewritten:
SELECT status, count(*), sum(total_cents) FROM orders WHERE created_at >= date '2026-11-30' - :d AND created_at < date '2026-11-30' - :d + 1 GROUP BY status;
Both versions for 23 gave the same three rows (cancelled 20, delivered 1663, shipped 155).
With EXPLAIN (ANALYZE, BUFFERS), the second of two runs each (the daily report for 7 November, - 23, both times; its “before” was measured later than task 3’s run, with more pages already in Postgres’s cache, so it differs from task 3’s 414 ms: compare runs made the same way):
| Query | Before | After | Plan after |
|---|---|---|---|
| login (customer 22756) | 118.578 ms | 0.118 ms | Bitmap Index Scan on customers_lower_email_idx |
| daily report | 347.168 ms | 2.361 ms | Index Scan using orders_status_created_at_idx |
Now the whole app. In psql, SELECT pg_stat_statements_reset(); empties the counts; then run the same pgbench
command as in task 2, and list the top 5 again.
number of transactions actually processed: 168009
tps = 2801.289051 (without initial connection time)
calls | total_ms | mean_ms | query
--------+----------+---------+----------------------------------------------------
63474 | 59141 | 0.9 | SELECT id, status, total_cents, created_at FROM or
101167 | 16866 | 0.2 | SELECT id, country FROM customers WHERE lower(emai
3368 | 7837 | 2.3 | SELECT status, count(*), sum(total_cents) FROM ord
2,801 runs a second instead of 16. A second walk-through on the same Pi gave 15 and 3,512: these counts vary from run to run, so compare your own before and after, not yours with these. My orders is now first by total time, at 0.9 ms a call: a top list always has a top. Stop when each line is fast for what it does.
Finish your report: for login.sql and daily-report.sql, the mean before and after, the fix, and the runs per
second before and after.
Check your work
./lab check p3
All 14 checks should pass. The checker reruns your login.sql and daily-report.sql with fixed values, compares the
daily report’s answer with the original query’s for three days, and reads your report.
You can now do what this course set out to: take a slow query from the logs, run EXPLAIN ANALYZE on it, and say
why it’s slow and what would fix it. To remove everything this course made:
docker rm -f explain-db && docker volume rm explain-data && rm -rf ~/pg-explain.
Next: back to the front page, or lesson 5’s checklist.