Interview Question: "Walk me through reading an EXPLAIN ANALYZE output. How do you identify a sequential scan bottleneck? What does 'Buffers' tell you?" â Asked at PostgreSQL, CitusData, Amazon Aurora for Database Engineer roles
âšī¸
Difficulty: Advanced | Companies: PostgreSQL, CitusData, Amazon Aurora, Google Cloud SQL, Azure SQL | Time: 60-75 minutes
Reading a plan is reading a story about rows
EXPLAIN shows what the planner intends; EXPLAIN ANALYZE runs the query and reports what actually happened, and the gap between those two numbers is where most performance work begins. A plan is a tree: every node reports an estimated cost, an estimated row count, the actual time, and â once buffers are enabled â how many pages came from memory and how many from disk. Reading top-down tells you the shape of the work; reading bottom-up tells you where the time went, because a node's actual time includes the time of its children. This lesson covers the option set, the anatomy of a real plan, the cost constants behind the estimates, the bottleneck patterns worth memorizing, and how to compare two plans honestly before and after a change.
EXPLAIN Options
-- Basic EXPLAIN
EXPLAIN SELECT * FROM orders WHERE customer_id = 1234;
-- EXPLAIN with ANALYZE (executes query)
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 1234;
-- Full analysis with BUFFERS
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders WHERE customer_id = 1234;
-- JSON output for programmatic analysis
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT * FROM orders WHERE customer_id = 1234;
-- Verbose output
EXPLAIN (ANALYZE, VERBOSE)
SELECT * FROM orders WHERE customer_id = 1234;
Start with plain EXPLAIN, which is free because it executes nothing, and use it to check shape before you commit to a run. Adding ANALYZE executes the statement for real, so a statement with side effects â a write wrapped in a query, a function that mutates state â must be examined first, and on a production replica that distinction separates a read from an incident. BUFFERS is the option that changes the diagnosis: without it you can see that a scan is slow but not whether it is slow because the working set never fitted in memory. FORMAT JSON exists so tooling can diff two plans, while VERBOSE adds the output columns, which is how you discover that a query selecting seventeen columns reads all of them.
Reading EXPLAIN Output
-- Create sample tables
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(255),
region VARCHAR(20)
);
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INT REFERENCES customers(customer_id),
order_date DATE,
total_amount DECIMAL(12,2),
status VARCHAR(20)
);
CREATE INDEX idx_orders_customer ON orders(customer_id);
CREATE INDEX idx_orders_date ON orders(order_date);
-- Analyze a simple query
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.*, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date > '2024-01-01'
AND o.total_amount > 1000;
Output Explanation:
Hash Join (cost=2567.89..19456.78 rows=62500 width=64) (actual time=12.345..89.012 rows=62489 loops=1)
Hash Cond: (o.customer_id = c.customer_id)
Buffers: shared hit=1234 read=567
-> Seq Scan on orders o (cost=0.00..15678.90 rows=250000 width=16) (actual time=0.012..45.678 rows=250000 loops=1)
Filter: ((order_date > '2024-01-01') AND (total_amount > 1000))
Rows Removed by Filter: 750000
Buffers: shared hit=890 read=345
-> Hash (cost=1234.56..1234.56 rows=10000 width=48) (actual time=8.901..8.901 rows=10000 loops=1)
Buckets: 16384 Batches: 1 Memory Usage: 1234kB
Buffers: shared hit=344 read=222
-> Seq Scan on customers c (cost=0.00..1234.56 rows=10000 width=48) (actual time=0.005..4.567 rows=10000 loops=1)
Buffers: shared hit=344 read=222
Planning Time: 0.234 ms
Execution Time: 89.567 ms
Read the sample above from the bottom up. The sequential scan on orders discards three quarters of a million rows after filtering, and that is the real story: the estimate claimed 250,000 rows would survive while 62,489 did, so the planner over-estimated roughly fourfold and chose a plan built for a much larger result. The hash join then spends 89 milliseconds in total, with about 12 milliseconds of that in build and probe setup, and the buffers line reports 567 pages read from disk against 1,234 served from cache â close to a third of the data was not resident. Three questions follow in order: is the row estimate wrong, would an index remove the discarded rows, and does the working set exceed the configured work memory. Answer them in that order, because refreshing statistics is cheap and reasoning backwards from a plan built on a wrong estimate is guesswork.
Cost Model Breakdown
-- Understand cost calculations
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id = 1234;
-- Check different join strategies
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.*, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id;
-- Compare with nested loop
SET enable_hashjoin = off;
SET enable_mergejoin = off;
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.*, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id;
RESET enable_hashjoin;
RESET enable_mergejoin;
Costs are estimates expressed in arbitrary units rather than milliseconds, and their only job is to let the planner rank alternatives against each other. The defaults â a sequential page at 1.0, a random page at 4.0, a CPU tuple at 0.01 â encode an assumption about rotating disks that still shapes every plan you read on solid state, which is why forcing an index scan is occasionally correct rather than always wrong. Startup cost is paid before the first row appears, so a query that reads five rows prefers the option with the smallest startup cost even when its total cost is higher. Compare totals only between plans returning the same rows: a plan that is cheaper because it scans fewer rows is not cheaper, it is answering a different question.
Identifying Bottlenecks
Common Bottleneck Patterns:
- Sequential Scan on Large Table
Seq Scan on orders (cost=0.00..15678.90 rows=250000)
Rows Removed by Filter: 750000
- Nested Loop with High Row Estimate
Nested Loop (cost=0.00..1234567.89 rows=1000000)
- Hash Join with High Memory
Hash (cost=123456.78..123456.78 rows=1000000)
Buckets: 2097152 Batches: 4 Memory Usage: 65536kB
-- Identify missing indexes
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE status = 'pending' AND region = 'North';
-- Check for implicit type casts
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id = '1234'; -- String instead of int
-- Analyze subquery performance
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id IN (
SELECT customer_id FROM customers WHERE region = 'North'
);
Each pattern above leaves a distinct fingerprint. A sequential scan that filters away most rows usually means a missing index or a predicate the planner cannot use â a function wrapped around the column, or a type mismatch such as a string compared to an integer column, both of which appear in the sample queries above. A nested loop whose estimated row count is a million is a cardinality problem before it is a speed problem, because the inner side executes that many times. A hash join reporting multiple batches means the hash table did not fit in work memory and spilled; raising that setting for the session usually collapses batches back into one. Measure first, change one setting at a time, then re-run the same statement so you compare like plans.
Buffer Analysis
-- Analyze buffer usage
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders WHERE order_date > '2024-01-01';
-- Calculate I/O cost
WITH plan AS (
SELECT
(SELECT SUM(shared_hit) FROM pg_stat_statements) AS total_hit,
(SELECT SUM(shared_read) FROM pg_stat_statements) AS total_read
)
SELECT
total_hit,
total_read,
ROUND(total_hit::decimal / (total_hit + total_read) * 100, 2) AS hit_ratio,
ROUND(total_read::decimal / (total_hit + total_read) * 100, 2) AS miss_ratio
FROM plan;
Buffers turn a vague suspicion into arithmetic. Shared hits are pages served from the buffer cache, shared reads are pages fetched from storage, and the ratio between them is the cache hit rate for that statement â one query reading half its pages from disk feels slow even when its row estimates were perfect. Temporary blocks tell a second story: hash and sort operations that outran work memory spilled, and every spill is storage traffic nobody requested. When you compare two runs, compare buffer counts rather than elapsed time alone, because timing moves with machine load while buffer counts move with the query. A plan that got faster without reducing reads probably only got warmer.
Execution Plan Visualization
-- Get JSON plan for visualization tools
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT o.*, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date > '2024-01-01';
-- Output for explain.dalibo.com or pganalyze
/*
{
"Plan": {
"Node Type": "Hash Join",
"Parallel Aware": false,
"Relation Name": "orders",
"Alias": "o",
"Startup Cost": 2567.89,
"Total Cost": 19456.78,
"Plan Rows": 62500,
"Plan Width": 64,
"Actual Startup Time": 12.345,
"Actual Total Time": 89.012,
"Actual Rows": 62489,
"Actual Loops": 1,
"Shared Hit Blocks": 1234,
"Shared Read Blocks": 567
}
}
*/
Cost Estimation Accuracy
-- Compare estimated vs actual rows
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-03-31'
AND total_amount > 5000;
-- Check statistics accuracy
SELECT
attname,
n_distinct,
most_common_vals,
most_common_freqs,
histogram_bounds
FROM pg_stats
WHERE tablename = 'orders'
AND attname IN ('order_date', 'total_amount');
Estimation Error Formula:
Estimation error is a metric, not an anecdote. Compare the planner's row estimate with the actual count at the node where they diverge most, and once the error passes an order of magnitude the whole plan shape becomes unreliable: join order, join strategy, and the decision to sort all rest on those numbers. The usual causes are stale statistics, correlated columns whose independence assumption breaks, predicates wrapped in expressions the planner cannot evaluate, or a skewed distribution where the most common value covers a third of the table. The fix is mechanical â analyze the table, raise the statistics target for the column, or add an expression index for the predicate you keep writing â and the estimate should be re-checked after each change before anything else is touched.
Advanced: Plan Comparison
-- Compare plans before/after index
-- Before index
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE status = 'pending';
-- Create index
CREATE INDEX idx_orders_status ON orders(status);
-- After index
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE status = 'pending';
-- Compare with different settings
SET work_mem = '64MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders GROUP BY status;
SET work_mem = '4MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders GROUP BY status;
RESET work_mem;
Before-and-after comparisons are valid only when both plans return the same row counts. The sequence above also toggles planner settings, which is a technique for exploring the search space rather than a recommendation: those flags are escape hatches, and leaving one disabled in a pooled connection changes plans for every session that inherits it. Record the plan text, the buffer counts, the estimated-versus-actual rows, and wall time under comparable load. One more trap â the second run of a query is faster because its pages are already cached, so an index that looks like a win may only be a warm buffer pool. Either drain the cache for a cold measurement or ignore elapsed time and compare buffer counts instead.
Performance Metrics
| Metric | Good | Warning | Critical |
|---|---|---|---|
| Cache Hit Ratio | > 99% | 95-99% | < 95% |
| Seq Scan % | < 10% | 10-30% | > 30% |
| Index Scan % | > 90% | 70-90% | < 70% |
| Estimation Error | < 10% | 10-50% | > 50% |
-- Monitor query performance
SELECT
query,
calls,
total_time,
mean_time,
rows,
shared_hit,
shared_read
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 10;
-- Track slow queries
SELECT
pid,
now() - pg_stat_activity.query_start AS duration,
query,
state
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes';
âšī¸
Pro Tip: Use EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) with tools like pganalyze, explain.dalibo.com, or pgMustard for visual plan analysis.
The thresholds in the table assume a system serving interactive queries. A reporting warehouse will happily run thirty percent sequential scans on large aggregations where a bitmap scan would gain nothing, and a hit ratio near ninety-five percent may simply describe a table growing faster than memory rather than a signal to buy RAM. Turn such numbers into alerts only after a baseline exists: record the median for a week, alert on deviation from that median, and attach the offending plan to the alert. A metric without a plan attached tells you that something broke; the attached plan tells you what to do next.
Mathematical Cost Formulas
Sequential scan cost:
Where:
- = pages
- = sequential page cost (default 1.0)
- = rows
- = CPU tuple cost (default 0.01)
Index scan cost:
Where:
- = leaf pages
- = random page cost (default 4.0)
- = CPU operator cost (default 0.0025)
Hash join cost:
â ī¸
Common Mistake: Don't optimize based on cost numbers alone. Always compare actual execution times and buffer usage.
A loop that actually ends
Work the loop in one direction and stop when the evidence says to. Capture the plan, find the node with the largest gap between estimated and actual rows, decide whether the cause is selectivity, memory, or a missing access path, make exactly one change, and re-measure with the same statement. The loop ends in one of two places. Either the estimate matches reality within about a factor of two and the remaining time is irreducible for that shape of query, or the query should not be running at all â a statement scanning a billion rows to answer one dashboard tile belongs in a pre-aggregated table rather than in a faster plan. Optimization that does not start from the measured workload is decoration.
Common Mistakes
Running EXPLAIN ANALYZE on a statement that writes data
Fix: Use plain EXPLAIN first, and run ANALYZE only on read-only statements or replicas
Tuning settings before checking estimated versus actual rows
Fix: Fix statistics and access paths first, because a plan built on a wrong estimate cannot be tuned
Comparing wall-clock times from runs with different cache states
Fix: Compare shared buffer hits and reads, or force a cold cache before timing
Best Practices
- Read plans bottom-up to find where time is spent, then top-down to understand why
- Always enable BUFFERS when diagnosing a slow statement
- Capture plan text and row estimates alongside every change you record
- Treat planner enable flags as session-scoped experiments, never as configuration
- Attach the plan to the alert so the responder starts with evidence
Interview Questions
Q1: What does the actual time on a node include?
The time spent in that node plus everything beneath it in the plan tree, so children must be read before the parent makes sense
Q2: When should you force an index scan?
When the cost model is mispriced for your hardware â usually a small table or a selective predicate where random reads are cheaper than the default assumes
Q3: What causes a large difference between estimated and actual rows?
Stale statistics, correlated columns treated as independent, expressions the planner cannot evaluate, or skewed value distributions
Q4: What do shared reads tell you that timing does not?
Whether the statement actually fetched pages from storage, which stays stable under load while elapsed time varies with machine contention
Key Takeaways
- EXPLAIN estimates, EXPLAIN ANALYZE measures â the difference between them is the diagnosis
- Row estimates drive join order and strategy, so a wrong estimate invalidates the whole plan
- Buffers convert suspicion into arithmetic and stay comparable when wall time does not
- Fix statistics and access paths before adjusting memory or planner flags
- Stop optimizing when estimates match reality and route the query elsewhere when they cannot