Finding the Queries That Actually Matter
Enable pg_stat_statements, replay a mixed workload on the shop dataset, rank statements by total database time, fix the top two with the earlier lessons, and prove it with before-and-after numbers.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: replay a workload
- Step 2: fix the top two and only the top two
- Step 3: reset, replay, compare
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Indexing & Query Optimization
- How a B-Tree Index Finds Your Rows Concept · 20 min
- Reading an Execution Plan Node by Node Worked example · 30 min
- Lab: Designing Indexes for a Workload, Text Search Included Lab · 30 min
- Index-Friendly Rewrites and Fresh Statistics Lab · 25 min
- Finding the Queries That Actually Matter Lab · 20 min
- Check: Diagnose Three Slow Queries Knowledge check · 8 questions
What you will learn
- Find the most expensive statements with pg_stat_statements and verify an optimization with before-and-after measurements.
Prerequisites: SQL Fundamentals
01. Goal and setup
Optimising the query someone remembers being slow is how teams spend a week making the database 1% faster. Databases keep the score themselves: pg_stat_statements accumulates, per statement shape, how many times it ran and how much time it consumed. Ranking by total time — calls times mean — finds where the database's seconds actually go.
You need: the qopt-lab container, whose start command in the first lesson included -c shared_preload_libraries=pg_stat_statements. That library flag is the one step that cannot be done later without a restart, which is why it was there from the beginning. The same command also set -c pg_stat_statements.track_planning=on, so the view times planning as well as execution; the setting is off by default (timing every plan adds overhead on busy servers), and then the planning columns stay at zero. The extension then needs enabling per database; if you skipped it:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SHOW pg_stat_statements.track_planning; -- on: planning is timed too
-- start from a clean slate
SELECT pg_stat_statements_reset();The view also exists for production databases, where it is usually your first stop. On a real system do not reset it casually: the counters are the record. In this lab, reset is the point, because you are about to create a known workload.
02. Step 1: replay a workload
A realistic mix is running against the shop API: a dashboard counting 2026 orders (still the unrewritten shape from the previous lab), an exports feature paging deep with OFFSET, the customer history hot path, and product autocomplete. Replay it as an app would: the hot path sends its customer id as a bind parameter, and the other three statements are plain SQL text. Save the script as 05-workload.py (it uses the same venv as the earlier labs) and run uv run python 05-workload.py; the after argument is for step 3:
import sys, time
import psycopg
DSN = "host=localhost port=55461 dbname=qopt user=lab password=lab"
CUSTOMERS = [4242, 777, 1234, 9021, 3333]
FIXED = sys.argv[1:] == ["after"] # run "before" first, "after" in step 3
if FIXED: # step 3: the sargable range and the keyset page
DASHBOARD = ("SELECT count(*) FROM orders"
" WHERE created_at >= timestamptz '2026-01-01'"
" AND created_at < timestamptz '2027-01-01'")
EXPORT = ("SELECT id, customer_id, total FROM orders"
" WHERE id > 799980 ORDER BY id LIMIT 20")
else: # step 1: the shapes found in production
DASHBOARD = ("SELECT count(*) FROM orders"
" WHERE EXTRACT(YEAR FROM created_at) = 2026")
EXPORT = ("SELECT id, customer_id, total FROM orders"
" ORDER BY id LIMIT 20 OFFSET 799980")
t0 = time.perf_counter()
with psycopg.connect(DSN) as conn:
with conn.cursor() as cur:
for _ in range(40): # dashboard
cur.execute(DASHBOARD)
for _ in range(60): # deep export page
cur.execute(EXPORT)
for i in range(3000): # hot path, indexed
cur.execute(
"SELECT id, total, created_at FROM orders"
" WHERE customer_id = %s"
" AND created_at >= timestamptz '2026-08-01'"
" ORDER BY created_at DESC",
(CUSTOMERS[i % len(CUSTOMERS)],))
for _ in range(150): # autocomplete
cur.execute("SELECT id, name FROM products"
" WHERE name ILIKE '%less mo%'")
print(f"{'after' if FIXED else 'before'}: replay took"
f" {time.perf_counter() - t0:.1f} s")The script prints how long the replay took — about 25 s on the machine used for this page. Now rank what it cost. total_exec_time is the product of calls and mean; read it in milliseconds and imagine it as a share of one hour of production:
SELECT calls,
round(mean_exec_time::numeric, 1) AS mean_ms,
round(total_exec_time::numeric, 0) AS total_ms,
left(query, 55) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'qopt')
AND calls > 1
ORDER BY total_exec_time DESC
LIMIT 5; calls | mean_ms | total_ms | query
-------+---------+----------+---------------------------------------------------------
40 | 330.4 | 13215 | SELECT count(*) FROM orders WHERE EXTRACT($1 FROM creat
60 | 136.3 | 8180 | SELECT id, customer_id, total FROM orders ORDER BY id L
150 | 18.0 | 2700 | SELECT id, name FROM products WHERE name ILIKE $1
3000 | 0.0 | 48 | SELECT id, total, created_at FROM orders WHERE customer
(4 rows)The time columns differ on every machine, so the order of your rows may differ too. The calls and rows columns do not: they count what the replay did, and you can match them exactly:
SELECT calls, rows, left(query, 55) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'qopt')
AND calls > 1
ORDER BY calls, query; calls | rows | query
-------+--------+---------------------------------------------------------
40 | 40 | SELECT count(*) FROM orders WHERE EXTRACT($1 FROM creat
60 | 1200 | SELECT id, customer_id, total FROM orders ORDER BY id L
150 | 666600 | SELECT id, name FROM products WHERE name ILIKE $1
3000 | 18600 | SELECT id, total, created_at FROM orders WHERE customer
(4 rows)Read the ranking like an engineer. Two statements account for about 90% of database time, and neither is the one called 3,000 times: the hot path is already fast, because the composite index serves it. Note also how the text is stored: constants replaced by $1, $2, and even EXTRACT($1 FROM ...) — thousands of calls with different customer ids or page numbers fold into one row with their costs pooled. That is what makes the view usable at all. A caution: statements that differ in shape stay separate entries — up to PostgreSQL 17 that includes IN-lists of different lengths (PostgreSQL 18 squashes a list of constants into one entry) — so an ORM emitting varying SQL can smear one logical query across many rows.
Two more columns earn their keep once you look closely. plans and total_plan_time separate time spent choosing plans from time spent running them. They are filled only because track_planning is on in this lab; with the default (off) both read 0 for every statement. Look at them:
SELECT calls, plans,
round(total_plan_time::numeric, 1) AS plan_ms,
round(total_exec_time::numeric, 0) AS exec_ms,
left(query, 40) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'qopt')
AND calls > 1
ORDER BY calls, query; calls | plans | plan_ms | exec_ms | query
-------+-------+---------+---------+------------------------------------------
40 | 6 | 1.5 | 13215 | SELECT count(*) FROM orders WHERE EXTRAC
60 | 6 | 0.6 | 8180 | SELECT id, customer_id, total FROM order
150 | 6 | 118.7 | 2700 | SELECT id, name FROM products WHERE name
3000 | 11 | 0.8 | 48 | SELECT id, total, created_at FROM orders
(4 rows)Only 6 of the 40 dashboard calls were planned, and 11 of the 3,000 hot-path calls. psycopg 3 prepares a statement on the server once the same query has run five times (its prepare_threshold), and PostgreSQL then reuses the stored plan instead of planning again; the hot path took five more, because PostgreSQL plans a statement with parameters five times with the real values, then switches to one reusable generic plan if that plan is not much costlier than those five (as it was here). Here planning is a small share of the total, so it is not where this workload's time goes. For a cheap statement called millions of times without such reuse, the share can flip, and these two columns are the evidence for prepared statements or plan caching. And rows totals the rows each statement produced, which catches queries returning far more than their caller can use — usually a missing LIMIT or a filter applied in Python instead of SQL. Reading the view is a plain SELECT, so on production you can inspect it any time without touching load; just resist resetting counters that have been accumulating the evidence you will want tomorrow.
03. Step 2: fix the top two and only the top two
The fixes are already in your hands, and that is the point: measurement routes known problems to known solutions. The dashboard query gets the sargable range rewrite; the export page gets a keyset. The search statement is now the largest remaining cost at about 2.7 seconds per replay — and on reflection it already uses the trigram index from lesson 3 and runs in about 18 ms; whether to spend more on it is a product judgement, not an obvious win. That is a healthy stopping discipline: fix the measured top, then re-measure.
04. Step 3: reset, replay, compare
Deploy the rewrites. In the lab, uv run python 05-workload.py after swaps the two statements for their fixed shapes — the range predicate and WHERE id > 799980 ORDER BY id LIMIT 20, the keyset form of the same page. Reset the counters with SELECT pg_stat_statements_reset();, replay the identical mix with the after argument, and run the ranking query from step 1 again:
calls | mean_ms | total_ms | query
-------+---------+----------+---------------------------------------------------------
40 | 78.6 | 3146 | SELECT count(*) FROM orders WHERE created_at >= timesta
150 | 16.5 | 2469 | SELECT id, name FROM products WHERE name ILIKE $1
3000 | 0.0 | 52 | SELECT id, total, created_at FROM orders WHERE customer
60 | 0.0 | 1 | SELECT id, customer_id, total FROM orders WHERE id > $1
(4 rows)The calls and rows query from step 1 confirms that the replay did the same work — same calls, same rows returned — under the new statement shapes:
calls | rows | query
-------+--------+---------------------------------------------------------
40 | 40 | SELECT count(*) FROM orders WHERE created_at >= timesta
60 | 1200 | SELECT id, customer_id, total FROM orders WHERE id > $1
150 | 666600 | SELECT id, name FROM products WHERE name ILIKE $1
3000 | 18600 | SELECT id, total, created_at FROM orders WHERE customer
(4 rows)The same statements, re-ranked. The dashboard fell from 13,215 ms to 3,146 ms of total time (and now reads through the index); the export page fell from 8,180 ms to about 1 ms. The whole replay dropped from 24.9 s to 6.2 s of wall time on this machine — and the new number one is the search query, waiting for its own decision. Before you believe any of it, hold the measurement to a protocol:
- Run each version several times under the same conditions and take the median; the first run after a load pays disc I/O that later runs do not.
- Confirm the plan changed, not just the timing: one
EXPLAIN (ANALYZE, BUFFERS)before and after, as in the second lesson. - Record the machine, the version and the workload. Every number in this skill came from one four-core desktop running PostgreSQL 17; yours will differ, and production will differ again.
05. Troubleshooting
06. Check your understanding
07. Apply it
This closes the loop of the skill practice: replay your workload from lesson 3 on the ten-million-row table through pg_stat_statements, take the top three by total_exec_time, and repeat this lab's cycle — measure, fix with an index or rewrite from the earlier lessons, reset, replay, compare — until each of the three is at least five times cheaper. Submit the before-and-after rankings plus the EXPLAIN ANALYZE pairs. When you later wrap API tests around such a database, the API integration testing skill shows how to keep those tests fast and isolated.
08. Review prompt
Without looking back: explain why ranking by mean time misleads, and what column you sort by instead. Describe what statement normalisation does to constants, why IN-lists of different lengths become separate entries on PostgreSQL 17, and what PostgreSQL 18 changed. Then list the three parts of a trustworthy before-and-after measurement, and the one thing pg_stat_statements can never tell you about a slow query.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.