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
The query is parsed and rewritten (views expanded, subqueries flattened where possible).
The optimizer enumerates candidate plans: different access paths and join orders.
It estimates the cost of each using table statistics (row counts, value distributions, distinct counts) gathered by ANALYZE.
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
Node
Meaning
Typical concern
Seq Scan
Reads the whole table
Fine for small tables or large fractions; bad for selective filters
Index Scan
Walks the index, fetches rows
Good for few rows
Index Only Scan
Answers from the index alone
Best case for covered queries
Bitmap Heap Scan
Collects row locations, reads pages in order
Middle ground for medium selectivity
Nested Loop
For each outer row, probe inner
Great with few outer rows and an inner index
Hash Join
Builds a hash table on one input
Good for large unsorted inputs
Merge Join
Merges two sorted inputs
Good 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 ANALYZEactually 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.
Run EXPLAIN (ANALYZE, BUFFERS): Get the actual plan with timings and I/O.
Find the slowest node: Look at actual time multiplied by loops.
Compare estimated vs actual rows: Large gaps point to stale or weak statistics.
Fix the root cause: Add an index, rewrite the query, or run ANALYZE.
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.