a query tuning casebook
ten slow queries, their EXPLAINs, and the one change that fixed each.
- address
- everything.deep_dives.tuning_casebook
- part
- part 18, deep dives and interviews
- chapter
- chapter 5 of 10
- reading time
- 17 min
ten slow queries on the shop dataset, each with its real plan before, the one change that fixed it, and the plan after. every one of them is a pattern from an earlier chapter: a missing index, an expression the index doesn't store, stale or blind statistics, a loop that should be a join, a page that should be a seek, a NOT IN, a sort that spills, a foreign key with no index, and an OR no index can answer.
the method is the same every time: read the plan, find the node doing the work, change one thing, read the plan again.
the picture
you know how "the query is slow" turns into adding random indexes until it isn't? the plan already tells you what's wrong, if you read it in the right order. EXPLAIN ANALYZE and BUFFERS is the whole toolkit: find the node with the most rows thrown away, the most buffers, the biggest gap between estimated and actual rows, or a loops count that's way too high.
think of a mechanic with a stethoscope. the engine (the plan) tells you which cylinder knocks. you don't rebuild the engine, you fix the one part. in every case below, the fix is one line.
- run it for real; TIMING OFF if you only want counts
- ├── rows removed by filter, hugea missing or unusable index: cases 1, 2, 9
- ├── estimated rows far from actualstatistics: cases 3, 4
- ├── loops = hundreds or thousandsa per-row subquery or rescan: cases 5, 7
- ├── rows read far more than returnedOFFSET, or an OR that blocks indexes: cases 6, 10
- └── Sort Method: external merge Diskwork_mem: case 8
every figure below is a real capture on the same postgres that runs in this page (shop has exact statistics and no secondary indexes). flip before and after: the table on top is the top plan node's rows, buffers and temp blocks, and the tree under it is the whole plan.
1. the missing index
- 1SELECT order_id, qty FROM order_items WHERE product_id = 150;
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 81 | 159 | 0 |
case 1, before: no index on product_id, so postgres reads all of order_items and throws most of it away.
order_items and removes 24,861 rows to keep 81. after one CREATE INDEX: a bitmap scan.shop's tables only have their primary keys, so filtering on product_id means reading every page. a huge "rows removed by filter" next to a small output is the signature. an index on the filtered column turns 159 buffer reads into 67 (what an index actually is, when postgres uses an index).
one level deeperrun case 1 yourself
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, qty FROM order_items WHERE product_id = 150;
CREATE INDEX order_items_product_id ON order_items (product_id);
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, qty FROM order_items WHERE product_id = 150;2. a function on the column
- 1SELECT id, name FROM customers WHERE lower(email) = 'ada@example.com';
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 1 | 24 | 0 |
case 2, before: there's a unique index on email, but the query asks about lower(email), which the index doesn't store.
email has a unique index. after: an expression index on lower(email), and the same WHERE uses it.the unique index stores email, not lower(email), so it can't answer the question asked. the fix is to index the expression the query actually uses, spelled the same way (partial and expression indexes, why isn't my index used?). the same goes for created_at::date = …, coalesce(x, 0) = … and anything else that wraps the column: rewrite the predicate as a range on the bare column, or index the expression.
one level deeperrun case 2 yourself
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, name FROM customers WHERE lower(email) = 'ada@example.com';
CREATE INDEX customers_lower_email ON customers (lower(email));
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, name FROM customers WHERE lower(email) = 'ada@example.com';3. stale statistics
the setup is a table loaded in two batches: the undelivered orders first, then ANALYZE, then 9,352 delivered ones that nobody analyzed. the browser engine has no autovacuum, so nothing fixes that behind your back; on a real server, a big load right before a query does the same thing until autovacuum catches up.
- 1CREATE TABLE recent AS SELECT * FROM orders WHERE status <> 'delivered' ORDER BY id;
- 2CREATE INDEX recent_status ON recent (status);
- 3ANALYZE recent;
- 4INSERT INTO recent SELECT * FROM orders WHERE status = 'delivered' ORDER BY id;
- 5
- 6SELECT id, customer_id FROM recent WHERE status = 'cancelled';
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 317 | 85 | 0 |
case 3, before: the statistics still say half the rows are cancelled, so the planner expects thousands and reads the whole table. it finds 317.
the giveaway is the estimate column: 3,368 expected, 317 actual. when estimates are off by 10x on a single table scan with a plain equality, suspect stale pg_stats first. run ANALYZE after bulk loads, as part of the load (when estimates go wrong).
one level deeperrun case 3 yourself
CREATE TABLE recent AS SELECT * FROM orders WHERE status <> 'delivered' ORDER BY id;
CREATE INDEX recent_status ON recent (status);
ANALYZE recent;
INSERT INTO recent SELECT * FROM orders WHERE status = 'delivered' ORDER BY id;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
SELECT id, customer_id FROM recent WHERE status = 'cancelled';
ANALYZE recent;
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
SELECT id, customer_id FROM recent WHERE status = 'cancelled';4. correlated columns
- 1SELECT count(*) FROM customers WHERE city = 'London' AND country = 'GB';
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 1 | 24 | 0 |
case 4, before: the planner multiplies the two selectivities as if city and country were independent, and underestimates.
the planner assumes columns are independent and multiplies their selectivities: P(London) × P(GB). but every London customer is in GB, so the second condition removes nothing, and the product undercounts by about 8x. extended statistics teach it the dependency (the independence assumption, extended statistics). here the fix only moves a number. in a query that joins this result to orders and order_items, an 8x underestimate is how you get a nested loop that should have been a hash join.
one level deeperrun case 4 yourself
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM customers WHERE city = 'London' AND country = 'GB';
CREATE STATISTICS customers_city_country (dependencies) ON city, country FROM customers;
ANALYZE customers;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM customers WHERE city = 'London' AND country = 'GB';5. N+1, inside one statement
an ORM that loads Berlin's customers and then asks for each one's order count is the N+1 problem: one query for the list, N more for the details. a correlated subquery in the SELECT list is the same shape inside one statement:
- 1SELECT c.name, (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.id) AS orders
- 2FROM customers AS c WHERE c.city = 'Berlin';
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 133 | 11063 | 0 |
case 5, before: a subquery per customer, the N+1 pattern inside one statement. the SubPlan runs once per Berlin customer, and each run scans orders.
loops=133 is the tell. postgres can't always flatten a subquery in the SELECT list into a join (how subqueries get planned), so write the join yourself: one pass over orders, grouped. in the application, the fix is the same idea: one query with a join, or one query with WHERE customer_id = ANY($1), instead of a loop.
one level deeperrun case 5 yourself
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT c.name, (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.id) AS orders
FROM customers AS c WHERE c.city = 'Berlin';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT c.name, count(o.id) AS orders
FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE c.city = 'Berlin'
GROUP BY c.id, c.name;6. OFFSET to keyset
- 1SELECT id, status FROM orders ORDER BY id OFFSET 9000 LIMIT 20;
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 20 | 102 | 0 |
case 6, before: page 451 of 20 orders with OFFSET. the index scan reads the 9,000 rows it skips.
OFFSET 9000 LIMIT 20. the index scan returns 9,020 rows and the Limit throws away 9,000. after: WHERE id > 9000 starts the index scan at the right place and stops after 20.OFFSET doesn't skip rows, it reads and discards them, so page 451 costs 451 pages' worth of work. keyset pagination remembers the last key of the previous page and seeks past it, so every page costs the same (4 buffers here, against 102). the price: no "jump to page 451", and the sort key must be unique (add the id as a tiebreaker) (keyset pagination, LIMIT and OFFSET).
one level deeperrun case 6 yourself
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, status FROM orders ORDER BY id OFFSET 9000 LIMIT 20;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, status FROM orders WHERE id > 9000 ORDER BY id LIMIT 20;7. NOT IN to NOT EXISTS
- 1SET work_mem = '64kB';
- 2
- 3SELECT count(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 1 | 107 | 8374 |
case 7, before: NOT IN can't become an anti join (NULLs), and its hash doesn't fit, so the subquery's rows are rescanned for every customer.
work_mem = 64kB: NOT IN materializes the subquery and rescans it for each of 2,000 customers, 8,356 temp blocks read. after: NOT EXISTS is a hash anti join. both find 38 customers.NOT IN has to return no rows at all if the subquery produces a NULL (the NOT IN trap), so postgres can't turn it into an anti join. it runs it as a SubPlan instead: hashed if the subquery fits in work_mem, a rescan per outer row if it doesn't. the 64kB here stands in for a subquery too big to hash. NOT EXISTS has no NULL problem, so it becomes a hash anti join at any size. it's the faster spelling and the correct one.
one level deeperrun case 7 yourself
SET work_mem = '64kB';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM customers AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);8. a sort that spills
- 1SET work_mem = '64kB';
- 2
- 3SELECT order_id, line_no, unit_price FROM order_items ORDER BY unit_price DESC, order_id, line_no;
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 24942 | 168 | 306 |
case 8, before: the sort doesn't fit in work_mem, so it spills to disk and merges.
SET work_mem = '8MB': quicksort in 1,292 kB of memory.when a sort's input doesn't fit in work_mem, postgres writes sorted runs to temp files and merges them (sorting and work_mem). Sort Method: external merge Disk and temp blocks in BUFFERS say so. raise work_mem for that query or role (SET LOCAL work_mem inside a transaction), not globally: it's per sort and per hash node, per connection, so a global bump multiplies. or make the sort unnecessary with an index in the right order (indexes for ORDER BY).
one level deeperrun case 8 yourself
SET work_mem = '64kB';
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, line_no, unit_price FROM order_items ORDER BY unit_price DESC, order_id, line_no;
SET work_mem = '8MB';
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, line_no, unit_price FROM order_items ORDER BY unit_price DESC, order_id, line_no;9. a foreign key with no index
deleting a customer is fast to write and slow to run: orders.customer_id references customers, so for every deleted customer the foreign key's trigger has to check no order still points at it. postgres indexes the referenced side (the primary key) automatically, never the referencing side (foreign keys).
DELETE FROM customers WHERE id = 7; -- Ming Li, who never orderedthe check is a query of its own, run once per deleted row. it's this one (the shape is in postgres's ri_triggers.c):
- 1RESET work_mem;
- 2
- 3SELECT 1 FROM ONLY orders AS x WHERE customer_id = 7 FOR KEY SHARE OF x;
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 0 | 83 | 0 |
case 9, before: deleting a customer fires the foreign key's check on orders, and this is the query it runs. without an index on orders.customer_id it's a seq scan, once per deleted row.
EXPLAIN ANALYZE of the DELETE itself only shows the trigger as a line (Trigger for constraint orders_customer_id_fkey: calls=1), not its plan, which is why this one hides so well. index your foreign keys unless you're sure the parent is never deleted or updated.
one level deeperrun case 9 yourself
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
DELETE FROM customers WHERE id = 7;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT 1 FROM ONLY orders AS x WHERE customer_id = 7 FOR KEY SHARE OF x;
CREATE INDEX orders_customer_id ON orders (customer_id);
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT 1 FROM ONLY orders AS x WHERE customer_id = 7 FOR KEY SHARE OF x;10. an OR across two tables
- 1SELECT o.id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id
- 2WHERE c.email = 'ada@example.com' OR o.id = 5000;
| rowsint8 | shared buffersint8 | temp blocksint8 |
|---|---|---|
| 8 | 107 | 0 |
case 10, before: the OR spans two tables, so no index can answer it. both tables are read in full and joined, then filtered.
an OR inside one table can use two indexes at once (a BitmapOr, see bitmap scans). an OR whose halves are about different tables can't be pushed down to either one, so it's evaluated after the join, on every joined row. split it into a UNION of two queries that each have an indexable condition. UNION (not UNION ALL) removes the duplicate if a row matches both halves.
one level deeperrun case 10 yourself
CREATE INDEX orders_customer_id ON orders (customer_id);
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT o.id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id
WHERE c.email = 'ada@example.com' OR o.id = 5000;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT o.id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE c.email = 'ada@example.com'
UNION
SELECT o.id FROM orders AS o WHERE o.id = 5000;the pattern
all ten fixes were one line, and none of them was a hint or a setting change for the whole server. finding the slow query in the first place is finding slow queries (pg_stat_statements, auto_explain); forcing a plan when you truly have to is steering the planner.
keylines
- read the plan for: rows removed, estimate vs actual, loops, rows read vs returned, Disk.
- an index helps only if the query asks for what it stores: same column, same expression.
- bad estimates come from stale or blind statistics. ANALYZE, then CREATE STATISTICS.
- loops in the hundreds mean a per-row subquery or rescan. write the join.
- OFFSET reads what it skips. NOT IN can't anti-join. an OR across tables can't use an index.
- index foreign key columns, or deleting a parent row scans the child table.