SQL · Module 11 · Lesson 41 min read

EXPLAIN & EXPLAIN ANALYZE

EXPLAIN – the plan (estimates, doesn't run the query)

EXPLAIN SELECT …;

EXPLAIN ANALYZE – runs the query and shows real numbers

EXPLAIN (ANALYZE, BUFFERS) SELECT …; ⚠️ It really executes the statement. For UPDATE/DELETE, wrap it in BEGIN; … ROLLBACK;

Reading a plan

  • It's a tree: read from the most indented node up; children feed their parents
  • Each node shows:
    • cost=startup..total – the planner's estimate (arbitrary units)
    • rows= – estimated rows
    • With ANALYZE: actual time=… rows=… loops=…
  • Compare estimated vs actual rows: a big mismatch means bad statistics → run ANALYZE table

Scan types

NodeMeaning
Seq Scanreads the whole table (fine for small tables or most rows)
Index Scanwalks the index, fetches matching rows
Index Only Scananswers from the index alone (fastest)
Bitmap Index/Heap Scancollects matches from an index, then reads table pages in order

Join types

NodeGood when
Nested Loopsmall outer side + indexed inner side
Hash Joinlarge unsorted inputs, equality joins
Merge Joinboth inputs already sorted

Other nodes

Sort (watch for "external merge Disk" → needs more work_mem or an index), HashAggregate / GroupAggregate, Limit, Gather (parallel query)

Workflow for a slow query

  1. EXPLAIN ANALYZE it
  2. Find the node with the most time / rows
  3. Look for Seq Scans on big tables with selective filters → add or fix an index
  4. Check estimates vs actual → ANALYZE
  5. Re-run and compare

Tools: explain.depesz.com and explain.dalibo.com visualize plans.

Example

SQL
-- Setup: 200,000 orders and 5,000 customers
CREATE TABLE customers AS
SELECT g AS id, 'Customer ' || g AS name, (ARRAY['Kathmandu','Pokhara','Lalitpur'])[1 + g % 3] AS city
FROM generate_series(1, 5000) g;
ALTER TABLE customers ADD PRIMARY KEY (id);

CREATE TABLE orders AS
SELECT g AS id, 1 + (g % 5000) AS customer_id,
       round((random() * 3000)::numeric, 2) AS total,
       DATE '2026-01-01' + (g % 330) AS ordered_on
FROM generate_series(1, 200000) g;
ANALYZE customers; ANALYZE orders;

-- 1. Slow: no index on orders.customer_id
EXPLAIN ANALYZE
SELECT c.name, sum(o.total)
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE c.id = 42
GROUP BY c.name;
-- → Seq Scan on orders … Filter: (customer_id = 42)  Rows Removed by Filter: 199960

-- 2. Add the index and compare
CREATE INDEX idx_orders_customer ON orders (customer_id);
ANALYZE orders;

EXPLAIN ANALYZE
SELECT c.name, sum(o.total)
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE c.id = 42
GROUP BY c.name;
-- → Bitmap Index Scan on idx_orders_customer … (actual rows=40) — far faster

-- 3. EXPLAIN a big join: watch the join strategy
EXPLAIN
SELECT c.city, count(*)
FROM orders o JOIN customers c ON c.id = o.customer_id
GROUP BY c.city;
-- HashAggregate → Hash Join → Seq Scan on orders + Hash → Seq Scan on customers
-- (reading every row is correct here: we need them all)

-- 4. Safely analyze a DELETE
BEGIN;
EXPLAIN ANALYZE DELETE FROM orders WHERE ordered_on < '2026-02-01';
ROLLBACK;

-- 5. Machine-readable plan
EXPLAIN (FORMAT JSON) SELECT * FROM orders WHERE customer_id = 7;

DROP TABLE orders, customers;