// query optimisation

Reading an EXPLAIN plan: asking the database to show its homework

EXPLAIN looks like noise at first. Once you know three things to look for, it tells you exactly why a query is slow.

Published 12 Jul 202615 min read45 reads

When a query is slow, guessing why rarely works. EXPLAIN asks the database to show you exactly how it plans to run your query. EXPLAIN ANALYZE actually runs it and shows you what really happened, side by side with the plan.

🎯 Explain Like I'm Hired EXPLAIN is the database showing its homework: the steps it intends to take, and how expensive it thinks each step will be, before it runs anything. EXPLAIN ANALYZE goes further: it actually runs the query and shows you the real numbers next to those guesses, so you can see exactly where the database's guess was wrong. Example: if the plan estimated 8,000 rows but the real run found 7,842, that's a good guess and nothing to worry about. But if it guessed 8,000 and the real number was 2 million, that gap is usually the actual reason your query is slow.

EXPLAIN ANALYZE
SELECT customer_id, SUM(amount)
FROM orders
WHERE placed_at >= '2025-01-01'
GROUP BY customer_id;
HashAggregate  (cost=15234.00..15334.00 rows=8000 width=40) (actual time=120.3..125.1 rows=7842 loops=1)
  Group Key: customer_id
  ->  Seq Scan on orders  (cost=0.00..14200.00 rows=206800 width=12) (actual time=0.02..85.4 rows=204112 loops=1)
        Filter: (placed_at >= '2025-01-01')
        Rows Removed by Filter: 15888

Sign up to keep reading

Sign up free to unlock the worked examples, edge cases, and interview traps below.