Learn SQL
-- performance.explain_plans

EXPLAIN — Reading Query Plans in SQL

Ask the engine how it will run your query — then make it cheaper

--concept

EXPLAIN prints the query plan: the steps the engine intends to run, innermost first. Reading plans turns “this query feels slow” into a diagnosis: Seq Scan on a big table says “no usable index”; rows=N estimates say whether statistics are healthy; cost numbers rank alternatives. EXPLAIN ANALYZE additionally executes the query and reports real timings — the ground truth.

--how it works
1

Ask for the plan

EXPLAIN SELECT … — the engine returns its intended execution steps, cheapest-first estimates, without running anything.

2

Read innermost-out

The deepest node executes first and streams rows upward; indent depth is execution order.

3

Name the access paths

Seq Scan = whole table read. Index Scan = B-tree then row fetch. Bitmap Index Scan = index builds a bitmap, then heap reads in page order.

4

Trust but verify with ANALYZE

EXPLAIN ANALYZE actually executes and prints actual rows and time next to estimates — big gaps mean stale statistics (run ANALYZE).

5

Fix the expensive innermost node

Missing index, wrong join order, filter applied too late — the plan tells you which, and re-running it proves the fix.

--visualization
📋 STEP 1Seq Scan on employees(cost=0.00..12.50 rows=3)🔍 STEP 2Filter: department = Engineeringreads all 6 rows, keeps matches📊 STEP 3rows=3 estimatedvs actual rows=3 — healthy stats⏱ STEP 4Execution Time: 0.03 msEXPLAIN ANALYZE really ran itread the planSeq Scan … rows=3estimated onlytime unknown (not run)innermost node runs first;optimise the cheapest read first:index? fewer columns? filter earlier?EXPLAIN ANALYZE a SELECT only — never a write
Stage 1 / 4
EXPLAIN (no ANALYZE) shows the intended plan — estimates only, nothing executes, zero risk.
--example
query.sql
1EXPLAIN ANALYZE SELECT * FROM employees WHERE department = 'Engineering';
Result
plan
Seq Scan on employees (cost=0.00..12.50 rows=3) (actual time=0.01..0.02 rows=3 loops=1)
Filter: (department = 'Engineering'::text)
Planning Time: 0.1 ms
Execution Time: 0.03 ms

The engine chose a sequential scan — sensible here: 3 of 6 rows match, and reading the whole small table beats index lookups. rows=3 estimate matches actual rows=3, so statistics are healthy. On a million-row table with a rare department, the same plan would be the bug — and an index on department the fix.

--variants

Reading a Seq Scan

The plan of a full-table filter.

query.sql
1EXPLAIN ANALYZE SELECT * FROM employees WHERE department = 'Engineering';
Result
plan
Seq Scan on employees (cost=0.00..12.50 rows=3) (actual time=0.01..0.02 rows=3 loops=1)
Filter: (department = 'Engineering'::text)
Planning Time: 0.1 ms
Execution Time: 0.03 ms
1Seq Scan reads all six rows and filters — the right choice here: 3 of 6 rows match, an index would be slower.
2rows=3 estimated, rows=3 actual — the planner’s statistics are healthy.
3Same plan on a million-row table with a rare department would be the bug; the fix is an index on department.

cost=0.00..12.50 — what the numbers mean

Unitless, relative, and only for ranking plans.

query.sql
1EXPLAIN SELECT * FROM employees WHERE salary > 70000;
Result
plan
Seq Scan on employees (cost=0.00..12.50 rows=4)
Filter: (salary > 70000)
1startup cost .. total cost — page-fetch units, arbitrary but comparable.
2The planner picks the plan with the lowest total; EXPLAIN two formulations and compare their costs.
3cost does not predict milliseconds — actual time from ANALYZE does.

Estimates gone stale

rows=N is the planner’s guess — feed it truth.

query.sql
1EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'shipped';
2-- rows=1 estimated · rows=480000 actual
3ANALYZE orders;
4-- statistics refreshed, estimates (and plan) change
Result
plan
Seq Scan on orders (cost=0.00..34.00 rows=1) (actual time=0.4..95.3 rows=480000 loops=1)
Filter: (status = 'shipped'::text)
Rows Removed by Filter: 20
1Estimating 1 row when 480,000 match, the planner picked a nested loop for a follow-on join — catastrophically wrong here.
2ANALYZE re-samples the table; the next plan reflects the real distribution.
3Autovacuum in Postgres refreshes stats, but bulk loads outrun it — ANALYZE after big data changes.

Reading a join plan

Nested Loop vs Hash Join at a glance.

query.sql
1EXPLAIN SELECT e.name, d.location
2FROM employees e JOIN departments d ON e.department = d.dept_id;
Result
plan
Hash Join (cost=1.10..25.40 rows=6)
Hash Cond: (e.department = d.dept_id)
-> Seq Scan on employees e
-> Hash → Seq Scan on departments d
1The build side (departments, small) becomes an in-memory hash table.
2The probe side (employees) streams through it — one pass, O(N + M).
3Nested Loop appears when the outer is tiny and the inner is indexed; a Nested Loop over two big unindexed tables is a red flag.
--key facts
Estimates vs realityEXPLAIN is the plan; EXPLAIN ANALYZE actually runs it — never ANALYZE a writing statement
cost is unitlesscost numbers rank plans relative to each other; actual time is milliseconds
Statistics decayafter big loads, run ANALYZE so the planner knows the data shape
--use cases
Before optimising anything: never guess — EXPLAIN first
After adding an index: prove the plan switched from Seq Scan to Index Scan
Investigating “slow in production, fast locally” — plans differ with data volume and stats
Schema reviews: check the plans of your top-10 queries, not the DDL alone
--under the hood
Never EXPLAIN ANALYZE an INSERT/UPDATE/DELETE — ANALYZE executes it; wrap in a transaction and ROLLBACK, or use a copy schema.
MySQL shows plans as a table (EXPLAIN FORMAT=JSON for tree); Postgres visualisers like explain.dalibo.com render nested trees nicely.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.