skip to content

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
what to look at in a plan, in order. each one points at a case below.

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

query =
query.sql
  1. 1SELECT order_id, qty FROM order_items WHERE product_id = 150;
the result for before
rowsint8shared buffersint8temp blocksint8
811590
totals at the top plan node
the plan

case 1, before: no index on product_id, so postgres reads all of order_items and throws most of it away.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: a seq scan that reads all of 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
sqldb=shop
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;
output, from postgres 18.6
#1 · EXPLAIN
Seq Scan on order_items (actual rows=81.00 loops=1) Filter: (product_id = 150) Rows Removed by Filter: 24861 Buffers: shared read=159 Planning: Buffers: shared hit=30 read=3
#2 · CREATE INDEX
#3 · EXPLAIN
Bitmap Heap Scan on order_items (actual rows=81.00 loops=1) Recheck Cond: (product_id = 150) Heap Blocks: exact=65 Buffers: shared hit=65 read=2 -> Bitmap Index Scan on order_items_product_id (actual rows=81.00 loops=1) Index Cond: (product_id = 150) Index Searches: 1 Buffers: shared read=2 Planning: Buffers: shared hit=18 read=1

2. a function on the column

query =
query.sql
  1. 1SELECT id, name FROM customers WHERE lower(email) = 'ada@example.com';
the result for before
rowsint8shared buffersint8temp blocksint8
1240
totals at the top plan node
the plan

case 2, before: there's a unique index on email, but the query asks about lower(email), which the index doesn't store.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: a seq scan, though 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
sqldb=shop
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';
output, from postgres 18.6
#1 · EXPLAIN
Seq Scan on customers (actual rows=1.00 loops=1) Filter: (lower(email) = 'ada@example.com'::text) Rows Removed by Filter: 1999 Buffers: shared read=24 Planning: Buffers: shared hit=39 read=4 dirtied=1
#2 · CREATE INDEX
#3 · EXPLAIN
Bitmap Heap Scan on customers (actual rows=1.00 loops=1) Recheck Cond: (lower(email) = 'ada@example.com'::text) Heap Blocks: exact=1 Buffers: shared hit=1 read=2 -> Bitmap Index Scan on customers_lower_email (actual rows=1.00 loops=1) Index Cond: (lower(email) = 'ada@example.com'::text) Index Searches: 1 Buffers: shared read=2 Planning: Buffers: shared hit=19 read=1

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.

query =
query.sql
  1. 1CREATE TABLE recent AS SELECT * FROM orders WHERE status <> 'delivered' ORDER BY id;
  2. 2CREATE INDEX recent_status ON recent (status);
  3. 3ANALYZE recent;
  4. 4INSERT INTO recent SELECT * FROM orders WHERE status = 'delivered' ORDER BY id;
  5. 5
  6. 6SELECT id, customer_id FROM recent WHERE status = 'cancelled';
the result for before
rowsint8shared buffersint8temp blocksint8
317850
totals at the top plan node
the plan

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.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: statistics from the first batch say about half the rows are cancelled, so the planner expects 3,368 and picks a seq scan. after ANALYZE it expects 317, gets 317, and reads 7 buffers instead of 85.

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
sqldb=shop
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';
output, from postgres 18.6
#1 · SELECT 648
#2 · CREATE INDEX
#3 · ANALYZE
#4 · INSERT 0 9352
#5 · EXPLAIN
Seq Scan on recent (cost=0.00..171.06 rows=3368 width=8) (actual rows=317.00 loops=1) Filter: (status = 'cancelled'::text) Rows Removed by Filter: 9683 Buffers: shared hit=85 Planning: Buffers: shared hit=11
#6 · ANALYZE
#7 · EXPLAIN
Bitmap Heap Scan on recent (cost=6.74..95.70 rows=317 width=8) (actual rows=317.00 loops=1) Recheck Cond: (status = 'cancelled'::text) Heap Blocks: exact=5 Buffers: shared hit=7 -> Bitmap Index Scan on recent_status (cost=0.00..6.66 rows=317 width=0) (actual rows=317.00 loops=1) Index Cond: (status = 'cancelled'::text) Index Searches: 1 Buffers: shared hit=2 Planning: Buffers: shared hit=26

4. correlated columns

query =
query.sql
  1. 1SELECT count(*) FROM customers WHERE city = 'London' AND country = 'GB';
the result for before
rowsint8shared buffersint8temp blocksint8
1240
totals at the top plan node
the plan

case 4, before: the planner multiplies the two selectivities as if city and country were independent, and underestimates.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: estimated 1 rows on the scan, actual 159. after CREATE STATISTICS and ANALYZE: estimated 1. the plan shape doesn't change on a table this small; the estimate is what every join above it would inherit.

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
sqldb=shop
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';
output, from postgres 18.6
#1 · EXPLAIN
Aggregate (cost=54.05..54.06 rows=1 width=8) (actual rows=1.00 loops=1) -> Seq Scan on customers (cost=0.00..54.00 rows=20 width=0) (actual rows=159.00 loops=1) Filter: ((city = 'London'::text) AND (country = 'GB'::bpchar)) Rows Removed by Filter: 1841
#2 · CREATE STATISTICS
#3 · ANALYZE
#4 · EXPLAIN
Aggregate (cost=54.39..54.40 rows=1 width=8) (actual rows=1.00 loops=1) -> Seq Scan on customers (cost=0.00..54.00 rows=155 width=0) (actual rows=159.00 loops=1) Filter: ((city = 'London'::text) AND (country = 'GB'::bpchar)) Rows Removed by Filter: 1841

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:

query =
query.sql
  1. 1SELECT c.name, (SELECT count(*) FROM orders AS o WHERE o.customer_id = c.id) AS orders
  2. 2FROM customers AS c WHERE c.city = 'Berlin';
the result for before
rowsint8shared buffersint8temp blocksint8
133110630
totals at the top plan node
the plan

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.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: the SubPlan runs 133 times, once per Berlin customer, each time scanning orders: 11,063 buffers. after: one hash join and one aggregate, 107 buffers, same answer.

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
sqldb=shop
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;
output, from postgres 18.6
#1 · EXPLAIN
Seq Scan on customers c (actual rows=133.00 loops=1) Filter: (city = 'Berlin'::text) Rows Removed by Filter: 1867 Buffers: shared hit=10956 read=107 SubPlan 1 -> Aggregate (actual rows=1.00 loops=133) Buffers: shared hit=10956 read=83 -> Seq Scan on orders o (actual rows=4.83 loops=133) Filter: (customer_id = c.id) Rows Removed by Filter: 9995 Buffers: shared hit=10956 read=83 Planning: Buffers: shared hit=65 read=8 dirtied=1
#2 · EXPLAIN
HashAggregate (actual rows=133.00 loops=1) Group Key: c.id Batches: 1 Memory Usage: 32kB Buffers: shared hit=107 -> Hash Right Join (actual rows=648.00 loops=1) Hash Cond: (o.customer_id = c.id) Buffers: shared hit=107 -> Seq Scan on orders o (actual rows=10000.00 loops=1) Buffers: shared hit=83 -> Hash (actual rows=133.00 loops=1) Buckets: 1024 Batches: 1 Memory Usage: 10kB Buffers: shared hit=24 -> Seq Scan on customers c (actual rows=133.00 loops=1) Filter: (city = 'Berlin'::text) Rows Removed by Filter: 1867 Buffers: shared hit=24 Planning: Buffers: shared hit=34 read=5

6. OFFSET to keyset

query =
query.sql
  1. 1SELECT id, status FROM orders ORDER BY id OFFSET 9000 LIMIT 20;
the result for before
rowsint8shared buffersint8temp blocksint8
201020
totals at the top plan node
the plan

case 6, before: page 451 of 20 orders with OFFSET. the index scan reads the 9,000 rows it skips.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: 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
sqldb=shop
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;
output, from postgres 18.6
#1 · EXPLAIN
Limit (actual rows=20.00 loops=1) Buffers: shared read=102 -> Index Scan using orders_pkey on orders (actual rows=9020.00 loops=1) Index Searches: 1 Buffers: shared read=102 Planning: Buffers: shared hit=29 read=4 dirtied=1
#2 · EXPLAIN
Limit (actual rows=20.00 loops=1) Buffers: shared hit=4 -> Index Scan using orders_pkey on orders (actual rows=20.00 loops=1) Index Cond: (id > 9000) Index Searches: 1 Buffers: shared hit=4 Planning: Buffers: shared hit=3

7. NOT IN to NOT EXISTS

query =
query.sql
  1. 1SET work_mem = '64kB';
  2. 2
  3. 3SELECT count(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
the result for before
rowsint8shared buffersint8temp blocksint8
11078374
totals at the top plan node
the plan

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.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before, at 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
sqldb=shop
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);
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared read=107, temp read=8356 written=18 -> Seq Scan on customers (actual rows=38.00 loops=1) Filter: (NOT (ANY (id = (SubPlan 1).col1))) Rows Removed by Filter: 1962 Buffers: shared read=107, temp read=8356 written=18 SubPlan 1 -> Materialize (actual rows=2278.08 loops=2000) Storage: Disk Maximum Storage: 137kB Buffers: shared read=83, temp read=8356 written=18 -> Seq Scan on orders (actual rows=10000.00 loops=1) Buffers: shared read=83 Planning: Buffers: shared hit=49 read=8 dirtied=1
#3 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared hit=107 -> Hash Right Anti Join (actual rows=38.00 loops=1) Hash Cond: (o.customer_id = c.id) Buffers: shared hit=107 -> Seq Scan on orders o (actual rows=10000.00 loops=1) Buffers: shared hit=83 -> Hash (actual rows=2000.00 loops=1) Buckets: 2048 Batches: 1 Memory Usage: 63kB Buffers: shared hit=24 -> Seq Scan on customers c (actual rows=2000.00 loops=1) Buffers: shared hit=24 Planning: Buffers: shared hit=111 read=6

8. a sort that spills

query =
query.sql
  1. 1SET work_mem = '64kB';
  2. 2
  3. 3SELECT order_id, line_no, unit_price FROM order_items ORDER BY unit_price DESC, order_id, line_no;
the result for before
rowsint8shared buffersint8temp blocksint8
24942168306
totals at the top plan node
the plan

case 8, before: the sort doesn't fit in work_mem, so it spills to disk and merges.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before, at 64kB: external merge, Disk, 592 kB on disk. after 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
sqldb=shop
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;
output, from postgres 18.6
#1 · SET
#2 · EXPLAIN
Sort (actual rows=24942.00 loops=1) Sort Key: unit_price DESC, order_id, line_no Sort Method: external merge Disk: 592kB -> Seq Scan on order_items (actual rows=24942.00 loops=1)
#3 · SET
#4 · EXPLAIN
Sort (actual rows=24942.00 loops=1) Sort Key: unit_price DESC, order_id, line_no Sort Method: quicksort Memory: 1292kB -> Seq Scan on order_items (actual rows=24942.00 loops=1)

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).

predict the output
DELETE FROM customers WHERE id = 7. customer 7 has no orders. what does postgres read in orders?
sql
DELETE FROM customers WHERE id = 7;   -- Ming Li, who never ordered

the 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):

query =
query.sql
  1. 1RESET work_mem;
  2. 2
  3. 3SELECT 1 FROM ONLY orders AS x WHERE customer_id = 7 FOR KEY SHARE OF x;
the result for before
rowsint8shared buffersint8temp blocksint8
0830
totals at the top plan node
the plan

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.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
the foreign key's check for one deleted customer. before: a seq scan removes all orders. after an index on orders (customer_id): an index lookup that finds nothing in 2 page reads.

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
sqldb=shop
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;
output, from postgres 18.6
#1 · EXPLAIN
Delete on customers (actual rows=0.00 loops=1) -> Index Scan using customers_pkey on customers (actual rows=1.00 loops=1) Index Cond: (id = 7) Index Searches: 1 Trigger for constraint orders_customer_id_fkey: calls=1
#2 · EXPLAIN
LockRows (actual rows=0.00 loops=1) Buffers: shared hit=83 -> Seq Scan on orders x (actual rows=0.00 loops=1) Filter: (customer_id = 7) Rows Removed by Filter: 10000 Buffers: shared hit=83
#3 · CREATE INDEX
#4 · EXPLAIN
LockRows (actual rows=0.00 loops=1) Buffers: shared read=2 -> Bitmap Heap Scan on orders x (actual rows=0.00 loops=1) Recheck Cond: (customer_id = 7) Buffers: shared read=2 -> Bitmap Index Scan on orders_customer_id (actual rows=0.00 loops=1) Index Cond: (customer_id = 7) Index Searches: 1 Buffers: shared read=2 Planning: Buffers: shared hit=15 read=1

10. an OR across two tables

query =
query.sql
  1. 1SELECT o.id FROM orders AS o JOIN customers AS c ON c.id = o.customer_id
  2. 2WHERE c.email = 'ada@example.com' OR o.id = 5000;
the result for before
rowsint8shared buffersint8temp blocksint8
81070
totals at the top plan node
the plan

case 10, before: the OR spans two tables, so no index can answer it. both tables are read in full and joined, then filtered.

real output, postgres 18.6 (PGlite 0.5.12) · casebook-1
before: both tables read in full, joined, and 9,992 joined rows filtered out by the OR. after: a UNION of two queries, each answered by an index (15 buffers, against 107).

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
sqldb=shop
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;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · EXPLAIN
Hash Join (actual rows=8.00 loops=1) Hash Cond: (o.customer_id = c.id) Join Filter: ((c.email = 'ada@example.com'::text) OR (o.id = 5000)) Rows Removed by Join Filter: 9992 Buffers: shared hit=83 read=24 -> Seq Scan on orders o (actual rows=10000.00 loops=1) Buffers: shared hit=83 -> Hash (actual rows=2000.00 loops=1) Buckets: 2048 Batches: 1 Memory Usage: 116kB Buffers: shared read=24 -> Seq Scan on customers c (actual rows=2000.00 loops=1) Buffers: shared read=24 Planning: Buffers: shared hit=162 read=15 dirtied=1
#3 · EXPLAIN
Unique (actual rows=8.00 loops=1) Buffers: shared hit=11 read=4 -> Sort (actual rows=8.00 loops=1) Sort Key: o.id Sort Method: quicksort Memory: 17kB Buffers: shared hit=11 read=4 -> Append (actual rows=8.00 loops=1) Buffers: shared hit=11 read=4 -> Nested Loop (actual rows=7.00 loops=1) Buffers: shared hit=10 read=2 -> Index Scan using customers_email_key on customers c (actual rows=1.00 loops=1) Index Cond: (email = 'ada@example.com'::text) Index Searches: 1 Buffers: shared hit=1 read=2 -> Bitmap Heap Scan on orders o (actual rows=7.00 loops=1) Recheck Cond: (customer_id = c.id) Heap Blocks: exact=7 Buffers: shared hit=9 -> Bitmap Index Scan on orders_customer_id (actual rows=7.00 loops=1) Index Cond: (customer_id = c.id) Index Searches: 1 Buffers: shared hit=2 -> Index Only Scan using orders_pkey on orders o_1 (actual rows=1.00 loops=1) Index Cond: (id = 5000) Heap Fetches: 0 Index Searches: 1 Buffers: shared hit=1 read=2 Planning: Buffers: shared hit=12

the pattern

quick check
a plan shows a Nested Loop with loops=40,000 on its inner Seq Scan, and the outer node estimated 3 rows. what do you check first?

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.