Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 16 / Topic 1 of 5

EXPLAIN: the plan, before running

Put EXPLAIN before any query and Postgres shows its plan — the tree of steps it would execute — without running it:

EXPLAIN SELECT * FROM big_orders WHERE customer_id = 42;  -- output varies per run
                           QUERY PLAN                           
----------------------------------------------------------------
 Seq Scan on big_orders  (cost=0.00..4082.00 rows=40 width=18)
   Filter: (customer_id = 42)
(2 rows)

How to read a node, left to right:

  • The node type (Seq Scan) — the operation.
  • cost=0.00..4082.00 — the planner's startup and total cost, in abstract units (page reads ≈ 1.0). Costs exist to compare candidate plans against each other, not to predict milliseconds.
  • rows=40 — the estimate of rows this node will emit, straight out of pg_stats (5,000 distinct customers over 200,000 rows comes to about 40 each). This number drives every choice the planner makes.
  • width=18 — average row bytes.

Plans are trees: indented children feed their parents, and execution reads innermost-first. For this stage's lessons we'll usually add (COSTS OFF) — the shapes stay, the per-sample noise goes.

🧪 Quick quiz — answer from memory, then check.

  1. Does plain EXPLAIN run the query?
  2. Where does rows=40 come from?
Show the answers
  1. No — it plans only. (EXPLAIN ANALYZE runs it.)
  2. The statistics: estimated distinct values and histograms from pg_stats — an educated guess, not a count.

Done here? The practice set for Part 16 — 4 exercises with solutions — is on the part page.

Search the guide