Overview and Core Concept
EXPLAIN reports what the cost-based query planner estimates it will do. EXPLAIN ANALYZE executes the statement and captures what actually happened. The difference between the two is the difference between diagnosing an incident with telemetry versus guessing.
In this guide, you will master reading execution plans line by line, evaluating the 10 most common plan nodes, decoding cost, rows, actual time, and buffers metrics, and avoiding the 7 classic interpretation mistakes. By the end, you will recognize which number constitutes an alarm, where to look first, and which remediation will yield measurable latency reduction.
Scenario
Staging vs Production Divergence. A query completes in 40 milliseconds in the test environment, but degrades to 4.2 seconds in production. Both environments share identical schema definitions, identical indexes, and the same PostgreSQL major version.
Why the discrepancy? The immediate developer reflex is to add another index, increase server RAM, or rewrite the application query. Yet nobody has inspected the execution plan.
When you deconstruct the plan, the ground truth emerges: the staging table holds 10,000 rows, while the production table holds 12 million rows. In staging, the planner chose an Index Scan. In production, the planner selected a Seq Scan because catalog statistics were stale. The problem was never missing indexes; it was statistics obsolescence. EXPLAIN ANALYZE reveals this disparity in 10 seconds.
The Core Distinction: EXPLAIN vs EXPLAIN ANALYZE
Without mastering this difference, plan analysis is unreliable.
▸EXPLAIN (Dry Run)
EXPLAIN does not execute the target query. It solely models the execution path chosen by the planner based on current catalog statistics.
EXPLAIN SELECT * FROM orders WHERE customer_id = 123;The resulting cost and rows metrics are purely speculative mathematical estimates. There is no real execution duration and no actual row count.
▸EXPLAIN ANALYZE (Live Execution Telemetry)
EXPLAIN ANALYZE actually executes the query on the database engine, timing each individual plan node and measuring returned row sets.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 123;The output delivers ground-truth telemetry: actual time, actual rows, loops, and buffer hit/read counts. Always include `BUFFERS` in production diagnostics.
EXPLAIN ANALYZE executes the statement, running it on an UPDATE, DELETE, or INSERT will modify data in production. For mutating statements, wrap the command in an explicit transaction and roll it back:-- Safe execution harness for mutation statements
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'shipped' WHERE id = 123;
ROLLBACK;This harness allows you to extract runtime telemetry without committing modifications to persistent storage.
The Reading Order: Read Bottom-Up, Not Top-Down
Query plans appear intimidating because engineers reflexively read them from top to bottom. In reality, execution trees must be evaluated bottom-up and inside-out.
The innermost, bottom nodes represent the initial physical I/O scans where data is fetched from disk or RAM. The topmost node represents the final projection returned to the client socket.
Consider this execution tree:
Sort (cost=1234.56..1235.00 rows=180 width=48) (actual time=45.210..45.320 rows=180 loops=1)
Sort Key: created_at DESC
-> Seq Scan on orders (cost=0.00..1200.00 rows=180 width=48) (actual time=0.020..42.100 rows=180 loops=1)
Filter: customer_id = 123
Rows Removed by Filter: 1200000Anatomy of the Bottom-Up Read:
- 1Start at the leaf node:
Seq Scan on orders. - 2Examine the filter telemetry:
Rows Removed by Filter: 1200000. The storage engine read 1.2 million rows from disk/RAM only to discard all but 180 rows. This is massive computational and I/O waste. - 3Inspect node time: The leaf node consumed
42.100 msout of the query's total45.320 ms. - 4Evaluate parent node: The parent
Sortnode finished in45.320 ms. Its self-time is only45.320 - 42.100 = 3.22 ms.
Engineers reading top-down mistakenly blame the Sort node for the latency. Engineers reading bottom-up correctly diagnose the Seq Scan and missing predicate index.
The 5 Critical Plan Metrics
▸1. Cost
Displayed as cost=0.00..1200.00. The first figure is the start-up cost (time to retrieve the first row); the second is the total completion cost.
- •Cost is not milliseconds or seconds. It is a unitless, arbitrary measurement defined by planner cost parameters (such as
seq_page_cost = 1.0,random_page_cost = 4.0, andcpu_tuple_cost = 0.01). - •The planner uses cost strictly to rank candidate query trees. A lower cost does not guarantee faster real-world execution if catalog statistics are skewed.
▸2. Rows: Estimated vs Actual
rows=180 (planner estimate)
actual rows=180 (telemetry)The ratio between estimated rows and actual rows is the most critical metric in the plan.
- •If estimated = 10 and actual = 1,000,000: The planner assumes the dataset is tiny and may pick a
Nested Loopjoin orIndex Scan, which degrades severely at scale. - •Rule of Thumb: A 10x discrepancy signals stale statistics. A 100x discrepancy indicates catalog failure. Immediately execute
ANALYZE orders;.
▸3. Actual Time
Formatted as actual time=0.020..42.100. The first figure is milliseconds to first row; the second is milliseconds to complete the node.
- •Crucial Rule:
actual timeis cumulative. A parent node's recorded time includes the duration of all its child sub-trees. - •To compute a node's true self-cost, subtract the maximum runtime of its child nodes from the node's total time.
▸4. Loops
The loops=N metric specifies how many times that specific plan node was executed.
- •When
loops=1,actual timerepresents total time. - •When
loops=1000, the recorded `actual time` and `actual rows` are averages per loop iteration. - •Total node time is calculated as:
actual time (stop) * loops. An inner node recordingactual time=8.0ms loops=1000consumed 8,000 milliseconds of compute time.
▸5. Buffers (I/O and Memory Footprint)
Never inspect a plan without the BUFFERS argument. Fast execution times on a local workstation often mask cold-cache catastrophes:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 123;Buffer Metrics:
- •
shared hit=120: Pages retrieved directly from PostgreSQL RAM (shared_buffers). Latency: microseconds. - •
shared read=5000: Pages read from operating system cache or physical disk. Latency: milliseconds. - •
shared dirtied/shared written: Pages modified or flushed to disk by this operation. - •
temp read/temp written: Work space memory exhausted; Sort or Hash spilled to temporary disk files. Direct indication that `work_mem` is insufficient.
10 Essential Plan Nodes Explained
▸1. Seq Scan (Sequential Table Scan)
Reads the entire physical relation from beginning to end.
- •Acceptable: Small lookups (< 1,000 rows) or queries retrieving > 25% of table tuples.
- •Defect: Present on multi-million row tables with large
Rows Removed by Filter. Indicates missing index.
▸2. Index Scan
Traverses a B-Tree index to find tuple pointers, then fetches each matching row from the table heap.
- •Acceptable: Highly selective predicates returning small row sets.
- •Limitation: Can incur random physical I/O if the heap is fragmented and the table is larger than RAM.
▸3. Index Only Scan
Retrieves requested data directly from the index leaves without accessing the underlying table heap.
- •Fastest access path available.
- •Watch out for `Heap Fetches`: If
Heap Fetchesis high, the table's Visibility Map is dirty, forcing heap checks for MVCC visibility. RunVACUUMto restore visibility flags.
▸4. Bitmap Index Scan + Bitmap Heap Scan
A two-stage hybrid approach for medium selectivity.
- •Stage 1 (Bitmap Index Scan): Evaluates index entries and constructs a bitmap of target page numbers in memory.
- •Stage 2 (Bitmap Heap Scan): Reads target pages in sequential physical disk order, converting random I/O into sequential I/O.
- •If
Rows Removed by Index Recheckis elevated,work_memwas too small to hold the exact bitmap, causing lossy compression.
▸5. Nested Loop Join
For each row emitted by the outer plan, the engine iterates over the inner relation.
- •Optimal: Outer relation is tiny (e.g., 5 rows) and inner relation is indexed on the join key.
- •Catastrophic: Outer relation yields 100,000 rows. Results in 100,000 iterations of the inner node.
▸6. Hash Join
Builds an in-memory hash table from the smaller relation (Inner), then streams the larger relation (Outer) past the hash table to match keys.
- •Optimal: High-volume equi-joins on large unindexed relations.
- •Memory Spill: If the hash table exceeds
work_mem * hash_mem_multiplier, it performs multi-batch partitioning spilling to disk (temp written).
▸7. Merge Join
Streams two pre-sorted relations simultaneously, joining matching values like a zipper.
- •Optimal: Both relations are pre-sorted (via indexes) on join keys.
- •Defect: If inputs require explicit
Sortnodes prior to merging, verify if Hash Join is faster.
▸8. Sort
Orders records for ORDER BY, GROUP BY, or DISTINCT.
- •Quicksort (Memory): Entire sort fits within
work_mem. Fast. - •External Merge (Disk): Spills to disk. Look for
Sort Method: external merge Disk: 45MB. Increasework_memor index the sort key.
▸9. Aggregate (HashAggregate vs GroupAggregate)
Computes summary statistics (COUNT, SUM, AVG).
- •
HashAggregateuses an in-memory hash map; requires adequatework_mem. - •
GroupAggregateoperates on pre-sorted input streams.
▸10. Memoize (PostgreSQL 14+)
Caches output tuples for parameterized inner sub-plans within a Nested Loop.
- •Evaluates
Cache HitsvsCache Misses. - •High hit ratios indicate the planner successfully eliminated redundant repetitive executions.
3 Real-World Incident Case Studies
▸Case Study 1: The 100x Row Estimation Failure
Index Scan on orders (cost=0.43..8.44 rows=1 width=48) (actual time=0.120..1200.500 rows=120000 loops=1)The query engine estimated 1 row, but processed 120,000 rows. The planner based join and memory allocation decisions on a microscopic dataset. Remediation: Execute ANALYZE orders;. If estimation errors persist on skewed columns, increase statistics targets: ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;.
▸Case Study 2: Sort Spilling to External Disk
Sort (cost=5000.00..5500.00 rows=200000 width=48) (actual time=1200.000..1800.000 rows=200000 loops=1)
Sort Key: created_at DESC
Sort Method: external merge Disk: 45678kBSorting 200,000 records required 45MB of disk write/read cycles, adding 1.8 seconds of latency. Remediations:
- 1Create a B-Tree index on the sort key:
CREATE INDEX CONCURRENTLY idx_orders_created ON orders (created_at DESC);. This provides pre-ordered data, eliminating theSortnode entirely. - 2For batch analytical sessions, increase memory:
SET work_mem = '64MB';.
▸Case Study 3: The Multiplier Effect in Nested Loops
Nested Loop (cost=0.00..999999.00 rows=100000 width=48) (actual time=0.050..8900.000 rows=100000 loops=1)
-> Seq Scan on customers (actual time=0.010..10.000 rows=1000 loops=1)
-> Index Scan on orders (actual time=0.001..8.000 rows=100 loops=1000)The inner Index Scan executed 1,000 times (loops=1000). Although each iteration took only 8ms, cumulative latency reached 8.9 seconds. Remediation: Evaluate catalog statistics to allow the planner to select a Hash Join, or batch customer lookups into an array.
MySQL 8.4 Telemetry Equivalents
MySQL 8.0.18+ provides EXPLAIN ANALYZE formatted as a tree:
EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 123;Key MySQL Flags:
- •
type: ALL: Equivalent to PostgreSQLSeq Scan. - •
type: ref/range: Equivalent to B-Tree Index Scans. - •
Extra: Using filesort: Indicates sorting exceededsort_buffer_sizeand spilled to disk. - •
Extra: Using temporary: Intermediate grouping/sorting required an internal temporary table.
The diagnostic principle remains identical: compare estimates with actual telemetry, find the most expensive physical node, and execute a single targeted remediation.
7 Classic Interpretation Mistakes
- 1Focusing Solely on Cost: Cost is a synthetic planner metric, not real-time latency.
- 2Accepting Dry-Run `EXPLAIN` as Reality: Dry-run plans do not reflect data distribution shifts or memory cache hits.
- 3Omitting `BUFFERS`: Without buffers telemetry, you cannot distinguish between fast in-memory execution and cold-cache disk I/O bottlenecks.
- 4Reading Top-to-Bottom: Parent nodes inherit child node latencies. Leaf nodes reflect root causes.
- 5Running Unsafe `EXPLAIN ANALYZE` on Mutations: Never run un-bracketed mutations on production data. Wrap mutations in
BEGIN ... ROLLBACK;. - 6Drawing Conclusions from a Single Execution: The first run may populate
shared_buffers(cold cache). Always evaluate both cold and warm execution profiles. - 7Assuming Every Sequential Scan is Evil: On small relations or queries retrieving > 30% of a table, sequential scans are significantly faster than random index seek cycles.
Operational Checklist
- Query executed with
EXPLAIN (ANALYZE, BUFFERS) - Execution tree evaluated strictly bottom-up
- Estimated rows compared against actual returned rows
ANALYZEexecuted if estimation delta exceeds 10x- Most expensive physical node isolated without blaming parent nodes
- Shared hit vs shared read buffer cache ratio evaluated
work_memreviewed if temp written bytes are observed- Sort Method inspected for external merge disk spills
- Nested Loop nodes with high loop multipliers investigated
- Single remediation applied and plan re-evaluated
- Before and after execution plans archived side by side
Related Guides in Series
- •Pillar: Performance & Query Optimization
- •Cluster: Finding Top 20 Expensive Queries with pg_stat_statements
- •Cluster: The N+1 Query Problem and Connection Pool Saturation
- •Cluster: Vacuum, Analyze, and Autovacuum Tuning
- •Cluster: Index Architecture: B-Tree, Hash, GiST, GIN, BRIN Deep Dive