🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Reading Query Plans with EXPLAIN and ANALYZE

PerformanceOptimizationđŸŸĸ Free Lesson
Performance

Reading Query Plans with EXPLAIN and ANALYZE

A query plan is the database telling you exactly how it intends to answer your question — before or after it actually runs.

  • Cost units — why the planner's numbers are relative, not milliseconds
  • Actual vs estimated rows — the single most important comparison in any plan
  • Join strategies — nested loop, hash join, and merge join, and when each wins
  • A tuning loop — measure, change one thing, measure again Once you can read a plan, performance work stops being guesswork.

Prerequisites

  • !Basic SELECT, WHERE, and JOIN syntax
  • !What indexes are and how B-tree indexes work
  • !The difference between a clustered and non-clustered index (helpful, not required)

What You'll Learn

  • 1Explain what the planner's cost numbers actually represent
  • 2Run EXPLAIN (ANALYZE, BUFFERS) and interpret every major line
  • 3Spot row-estimate blowups, useless indexes, and bad join choices
  • 4Apply a repeatable loop for diagnosing and fixing slow queries

The Planner in 60 Seconds

Before PostgreSQL runs your query it builds a plan: a tree of operations such as sequential scans, index scans, joins, sorts, and aggregates. The planner estimates the cost of every candidate plan using statistics about your tables — row counts, value distributions, correlation between columns — and picks the cheapest estimated plan. Cost units are arbitrary and relative: a cost of 1,000 in one plan means something only when compared with another plan's cost for the same query. Milliseconds appear only when you run the plan and measure it.

This split between estimated and actual is the key to everything that follows. If the planner believes a filter keeps 10 rows but it actually keeps 100,000, every decision built on that belief — join order, join strategy, whether to sort or index-walk — is wrong. Reading plans is mostly the art of finding those belief gaps.

EXPLAIN shows the plan without running it. EXPLAIN ANALYZE runs it and reports actual timings and row counts next to the estimates. You can also use EXPLAIN (ANALYZE, BUFFERS) to see how many pages were read from disk versus served from cache, which separates CPU-bound problems from I/O-bound ones.

EXPLAIN versus ANALYZE versus BUFFERS

Each mode answers a different question. Use the simplest one that answers yours.

CommandRuns the query?ShowsUse it when
EXPLAINNoEstimated plan and costsComparing planner choices quickly; checking indexes without side effects
EXPLAIN ANALYZEYesPlan plus actual time, rows, loopsConfirming what really happens; finding estimate errors
EXPLAIN (ANALYZE, BUFFERS)YesAbove plus shared hit/read blocksDiagnosing I/O pressure and cache misses
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)YesMachine-readable planFeeding tools, dashboards, or plan-diff scripts

Two cautions. First, EXPLAIN ANALYZE actually executes the statement, so running it on an UPDATE or DELETE will modify data (wrap it in a transaction and roll back if you only want the measurement). Second, planning time can matter too — very complex queries with dozens of joins may spend hundreds of milliseconds just choosing a plan, visible at the bottom of the output as Planning Time.

-- Measure a real query, then roll back so nothing changes
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.first_name, c.last_name, SUM(o.total) AS lifetime_value
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id
WHERE o.order_date >= DATE '2024-01-01'
GROUP BY c.id, c.first_name, c.last_name
HAVING SUM(o.total) > 500
ORDER BY lifetime_value DESC
LIMIT 20;
ROLLBACK;

Anatomy of a Plan Tree

PostgreSQL prints the plan as an indented tree: children execute first and feed rows into their parent. Read from the innermost (most indented) nodes outward. A typical line looks like this:

Architecture Diagram
Hash Join  (cost=482.10..1204.55 rows=8420 width=48)
  Hash Cond: (o.customer_id = c.id)
  Buffers: shared hit=3120 read=884
  ->  Seq Scan on orders o  (cost=0.00..612.00 rows=42100 width=24)
        Filter: (order_date >= '2024-01-01'::date)
        Rows Removed by Filter: 57900
        Buffers: shared hit=2100 read=884
  ->  Hash  (cost=312.00..312.00 rows=11200 width=20)
        Buckets: 16384  Memory Usage: 512kB
        Buffers: shared hit=1020
        ->  Seq Scan on customers c  (cost=0.00..312.00 rows=11200 width=20)
              Buffers: shared hit=1020

Three numbers on the parent line matter most: the estimated cost range, the estimated rows, and width (average row width in bytes). Under EXPLAIN ANALYZE each node gains an actual time window and an actual rows value that repeats per loop. If a node reports actual rows=1,000,000 but the estimate was rows=200, the planner dramatically underestimated the filter's selectivity — usually because statistics are stale or the expression is not something the planner models well (for example, a function applied to a column).

Join Strategies and When Each Wins

The planner picks among three join algorithms, and the choice often decides whether a query runs in 50 ms or 50 seconds.

StrategyHow it worksBest whenWarning sign
Nested loopFor each outer row, probe the inner sideInner side is a tiny index-backed lookup; outer row count is smallInner side is a sequential scan that runs once per outer row (loops in the thousands)
Hash joinBuild a hash table on the smaller input, stream the larger oneNeither input is pre-sorted; both are larger than cache-friendlyHash table spills to disk — watch Hash Batches and Disk Usage
Merge joinSort both inputs (or use pre-sorted index scans), then mergeBoth inputs arrive sorted on the join keyUp-front sort cost dominates when inputs were already usable via index

A nested loop with loops=400000 on the inner side is the classic disaster: the planner trusted a bad row estimate and picked a strategy that rescans too often. Fixing it usually means refreshing statistics, simplifying a filter so the planner can model it, or forcing better estimates with a join order the planner would choose once estimates improve.

Red Flags You Can Spot in Seconds

Some patterns are almost always a problem in production plans:

  • Seq Scan on a large filtered table — a Filter on an unindexed column means every row is read. Add a btree index on the filtered column, or reconsider the query if the filter is un-sargable (for example, WHERE LOWER(email) = ... cannot use a plain index on email).
  • Rows Removed by Filter in the millions — the predicate is evaluated too late or cannot use an index. Check data types: comparing a varchar column to a date literal forces conversion per row.
  • Massive actual-versus-estimated gaps — run ANALYZE table_name; to refresh statistics. For skewed data, extended statistics or a partial index may be needed.
  • Sort Node with huge Memory Usage and Disk Usage: ... — the work_mem budget was too small for the sort; either raise work_mem for the session or add an index that delivers pre-sorted rows.
  • Repeated identical subplans — consider materializing with a CTE (in older PostgreSQL versions) or a temporary table.

A Repeatable Tuning Loop

Performance work rewards discipline. Follow the same loop every time so you can tell which change helped.

  1. Capture the baseline: run EXPLAIN (ANALYZE, BUFFERS) inside a transaction and save the output.
  2. Identify the single most expensive node — usually the one with the largest actual time or the biggest buffer count.
  3. Form one hypothesis: stale statistics, missing index, bad join order, spilled sort, oversized result.
  4. Change exactly one thing — ANALYZE, one CREATE INDEX, one rewritten predicate — never three at once.
  5. Re-run and diff. If the plan improved but latency did not, the bottleneck is elsewhere (network, client rendering, connection pool).
-- Refresh statistics after a bulk load, then re-check the plan
ANALYZE orders;
ANALYZE customers;

-- Example of making a predicate sargable: index the column, filter on it directly
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date);

-- Now the nested-loop probe can use an index scan instead of rescanning
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, SUM(total)
FROM orders
WHERE order_date BETWEEN DATE '2024-01-01' AND DATE '2024-12-31'
GROUP BY customer_id;

How Other Dialects Report Plans

The ideas transfer even when syntax does not.

EngineCommandNotes
PostgreSQLEXPLAIN (ANALYZE, BUFFERS)Tree output; JSON and XML formats available
MySQL 8.0.18+EXPLAIN ANALYZETree output; earlier versions use tabular EXPLAIN
MySQL (classic)EXPLAIN FORMAT=JSONRicher cost and nested-loop detail than the table format
SQL ServerSET STATISTICS IO, TIME ON plus actual execution plan in SSMSLook at estimated versus actual rows in the XML plan
OracleEXPLAIN PLAN FOR then read PLAN_TABLE; DBMS_XPLAN.DISPLAY_CURSOR for actualsA-Rows column plays the role of actual rows

Whichever engine you use, the diagnostic questions are identical: did the engine use the index you expected, are the row estimates close to reality, and did join and sort strategies match the data shapes you have?

Common Mistakes

Treating cost numbers as milliseconds and optimizing the wrong node

Fix: Compare costs only within one plan; use actual time from ANALYZE for real-world numbers

Running EXPLAIN ANALYZE on UPDATE or DELETE in production and committing the changes

Fix: Wrap it in BEGIN and ROLLBACK, or test on a read replica

Seeing a sequential scan and adding an index reflexively

Fix: Check the table size and selectivity first — a seq scan is often the fastest plan for large fractions of a table

Ignoring loops= on inner nodes

Fix: Multiply time by loops; a 0.02 ms inner node looping 500,000 times is your real cost

Adding indexes without removing them

Fix: Every index slows writes; drop redundant single-column indexes once a composite index covers the same prefixes

Best Practices

  • Always capture a baseline plan before changing anything
  • Use EXPLAIN (ANALYZE, BUFFERS) on production-shaped data, not tiny development tables
  • Run ANALYZE after bulk loads so the planner works with fresh statistics
  • Prefer sargable predicates so indexes stay usable
  • Store golden plans as JSON in version control and diff them in CI for critical queries

Interview Questions

Q1: What is the difference between EXPLAIN and EXPLAIN ANALYZE?

EXPLAIN shows the planner's estimated plan without executing the statement. EXPLAIN ANALYZE executes it and adds actual time, actual rows, and loop counts beside each estimate, which reveals where estimates diverged from reality.

Q2: A plan shows a nested loop with loops=250000 on the inner node. What is wrong and how do you fix it?

The planner underestimated the outer row count and chose a nested loop whose inner side is re-executed per row. Refresh statistics, make the filter sargable, or rewrite the query so a hash join is chosen; verify with a new ANALYZE run.

Q3: When is a sequential scan the correct plan?

When the query needs a large fraction of the table — roughly more than a few percent — reading every page sequentially is cheaper than random index lookups, so the planner correctly picks a seq scan.

Key Takeaways

  • EXPLAIN is free to run; EXPLAIN ANALYZE executes the query, so protect writes with a transaction
  • Costs are relative planner units — actual time and rows are what you feel in production
  • The gap between estimated and actual rows is the first thing to investigate in any bad plan
  • Join strategy mismatches caused by stale statistics are a top cause of sudden slowdowns
  • Tune with a loop: baseline, one hypothesis, one change, re-measure
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement