Execution Plans

Difficulty: Intermediate

Question

What is a query execution plan, and how do you read one to tune a slow query?

Answer

An execution plan is the tree of steps the database's query optimizer chooses to run a SQL statement: which indexes or scans to use, the join order, the join algorithm, and where sorting or aggregation happens. You view the estimated plan with EXPLAIN and the real one, with actual row counts and timings, with EXPLAIN ANALYZE. Reading plans is the core skill for fixing slow queries.

How the optimizer builds a plan

  1. The query is parsed and rewritten (views expanded, subqueries flattened where possible).
  2. The optimizer enumerates candidate plans: different access paths and join orders.
  3. It estimates the cost of each using table statistics (row counts, value distributions, distinct counts) gathered by ANALYZE.
  4. It picks the cheapest estimated plan and executes it.

Because the choice relies on estimates, stale or misleading statistics are a top cause of bad plans.

Common plan nodes

NodeMeaningTypical concern
Seq ScanReads the whole tableFine for small tables or large fractions; bad for selective filters
Index ScanWalks the index, fetches rowsGood for few rows
Index Only ScanAnswers from the index aloneBest case for covered queries
Bitmap Heap ScanCollects row locations, reads pages in orderMiddle ground for medium selectivity
Nested LoopFor each outer row, probe innerGreat with few outer rows and an inner index
Hash JoinBuilds a hash table on one inputGood for large unsorted inputs
Merge JoinMerges two sorted inputsGood when both sides are already sorted

How to read EXPLAIN ANALYZE

  • Read from the innermost, most indented node outward; children feed parents.
  • Compare estimated rows vs actual rows. A big mismatch (estimate 10, actual 500,000) means bad statistics or correlated columns, and the optimizer probably picked the wrong join.
  • Check loops: per-node timings are per loop, so multiply by loops to get the total.
  • Look for Rows Removed by Filter on a scan: lots of rows read and thrown away suggests a missing index.
  • Look for Sort Method: external merge Disk, which means the sort spilled because work_mem was too small.
  • Use the BUFFERS option to see how many pages were read from cache vs disk. PostgreSQL 18 includes buffer info by default with ANALYZE.

Gotchas

  • EXPLAIN ANALYZE actually runs the statement. For UPDATE or DELETE, wrap it in BEGIN; ... ROLLBACK;.
  • Plans differ between your laptop and production because data size and statistics differ. Test on realistic data.
  • MySQL supports EXPLAIN ANALYZE since 8.0.18 (tree format); SQL Server uses actual execution plans in SSMS.
  • Visual tools like explain.depesz.com or explain.dalibo.com make large PostgreSQL plans easier to read.
Tuning a slow query with its plan. A repeatable loop: measure, find the expensive node, fix the cause, measure again.
  1. Run EXPLAIN (ANALYZE, BUFFERS): Get the actual plan with timings and I/O.
  2. Find the slowest node: Look at actual time multiplied by loops.
  3. Compare estimated vs actual rows: Large gaps point to stale or weak statistics.
  4. Fix the root cause: Add an index, rewrite the query, or run ANALYZE.
  5. Re-run and compare: Confirm the plan changed and time dropped.

Code examples

Before and after adding an index

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, amount_paise FROM payments
WHERE merchant_id = 77 AND status = 'FAILED';

-- Plan shows: Seq Scan on payments ... Rows Removed by Filter: 4,999,120
CREATE INDEX CONCURRENTLY payments_merchant_status_idx
  ON payments (merchant_id, status);

-- Safely inspect a DELETE plan without deleting anything
BEGIN;
EXPLAIN ANALYZE DELETE FROM payments WHERE created_at < now() - interval '3 years';
ROLLBACK;

The Seq Scan with millions of rows removed by filter is the signal; after the composite index the plan becomes a targeted Index Scan.

Key points

  • The plan shows access paths, join order, join algorithms, sorts and aggregations.
  • EXPLAIN shows estimates; EXPLAIN ANALYZE runs the query and shows actuals.
  • Estimated vs actual row mismatches usually mean stale or weak statistics.
  • EXPLAIN ANALYZE executes DML, so wrap it in a transaction and roll back.
  • Use BUFFERS to see cache hits vs disk reads.

Common follow-up questions

  • When would the optimizer choose a sequential scan even though an index exists?
  • What is the difference between a nested loop, hash join and merge join?
  • How do stale statistics cause bad plans, and how do you fix them?
  • What are extended statistics in PostgreSQL and when do they help?

Interview tips

  • Describe a real slow query you fixed using a plan: what node was slow, what you changed, and the result.
  • Mention estimated vs actual rows; it shows you understand why optimizers make mistakes.
  • Warn that EXPLAIN ANALYZE executes the statement; interviewers like that safety awareness.

Concepts covered

Execution Plan, EXPLAIN ANALYZE, Query Optimizer, Cardinality Estimation, Join Algorithms

More Database Design questions