Interview Question: "Explain the difference between a cost-based optimizer and a rule-based optimizer. How does PostgreSQL estimate row counts? What are statistics and how do they affect query plans?" â Asked at Oracle, Microsoft, Snowflake for Database Engineer roles
âšī¸
Difficulty: Advanced | Companies: Oracle, Microsoft, Snowflake, Databricks, Amazon Redshift | Time: 60-75 minutes
Cost Model Fundamentals
The query optimizer estimates cost using:
For a sequential scan:
For an index scan:
Costs are dimensionless units, not seconds. The planner never claims a query will take 18,334 milliseconds; it only claims that one candidate plan costs 18,334 units and another costs 2,400 units, and it picks the smaller number. That is why a plan can look "expensive" in EXPLAIN while still running in under a millisecond on warm cache, and why comparing cost figures across servers is meaningless unless the settings match.
Every term in those formulas is a run-time configurable constant:
| Setting | Default | What one unit buys |
|---|---|---|
seq_page_cost | 1.0 | One 8 KB page read in a sequential run |
random_page_cost | 4.0 | One 8 KB page read after a seek |
cpu_tuple_cost | 0.01 | Processing one heap tuple |
cpu_index_tuple_cost | 0.005 | Processing one index entry |
cpu_operator_cost | 0.0025 | Applying one operator during filtering or joining |
effective_cache_size | 4 GB | The planner's guess of OS cache available to it |
On NVMe storage the seek penalty that random_page_cost = 4.0 models largely disappears, and lowering it to 1.0 is the single most common optimizer tuning change: it moves the seq-scan-versus-index-scan crossover point from roughly 1% selectivity to roughly 3.5%, so index plans start winning on much broader predicates. Notice that effective_cache_size changes no actual memory usage â it only shifts how optimistic the planner is about pages it can read for free from the OS page cache.
-- Create sample tables for optimization analysis
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(12,2),
status VARCHAR(20),
region VARCHAR(50)
);
CREATE TABLE order_items (
item_id SERIAL PRIMARY KEY,
order_id INT REFERENCES orders(order_id),
product_id INT,
quantity INT,
unit_price DECIMAL(10,2)
);
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(255),
region VARCHAR(50),
credit_limit DECIMAL(12,2)
);
-- Generate sample data (1M orders)
INSERT INTO orders (customer_id, order_date, total_amount, status, region)
SELECT
(random() * 10000)::INT + 1,
CURRENT_DATE - (random() * 365)::INT,
(random() * 10000)::DECIMAL(12,2),
(ARRAY['pending', 'shipped', 'delivered', 'cancelled'])[floor(random()*4+1)],
(ARRAY['North', 'South', 'East', 'West'])[floor(random()*4+1)]
FROM generate_series(1, 1000000);
-- Generate order items
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
SELECT
order_id,
(random() * 1000)::INT + 1,
(random() * 10)::INT + 1,
(random() * 500)::DECIMAL(10,2)
FROM orders, generate_series(1, (random() * 5)::INT + 1);
-- Generate customers
INSERT INTO customers (name, email, region, credit_limit)
SELECT
'Customer ' || i,
'customer' || i || '@example.com',
(ARRAY['North', 'South', 'East', 'West'])[floor(random()*4+1)],
(random() * 50000)::DECIMAL(12,2)
FROM generate_series(1, 10000) i;
Understanding EXPLAIN Output
-- Basic EXPLAIN analysis
EXPLAIN SELECT * FROM orders WHERE region = 'North';
Output:
Seq Scan on orders (cost=0.00..18334.00 rows=250000 width=48)
Filter: (region = 'North')
Rows Removed by Filter: 750000
Cost Breakdown:
0.00= startup cost (before first row)18334.00= total cost (all rows processed)250000= estimated rows48= estimated row width in bytes
-- Detailed EXPLAIN with ANALYZE
EXPLAIN ANALYZE
SELECT o.order_id, o.total_amount, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.region = 'North'
AND o.total_amount > 1000;
Output:
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)
-> 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: ((region = 'North') AND (total_amount > 1000))
Rows Removed by Filter: 750000
-> 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
-> Seq Scan on customers c (cost=0.00..1234.56 rows=10000 width=48) (actual time=0.005..4.567 rows=10000 loops=1)
Planning Time: 0.234 ms
Execution Time: 89.567 ms
âšī¸
Key Metrics: Compare estimated rows vs actual rows. Large discrepancies indicate stale statistics or poor estimates.
Reading the two plans side by side answers most questions about plan health:
- The estimate of 250,000 rows for
region = 'North'against 1,000,000 total is exactly 0.25 selectivity, and the actual row count matched it, so the histogram for that column was refreshed recently. - The join estimated 62,500 rows and returned 62,489 â an error of 11 rows, or 0.018%. Estimate errors below roughly 10% rarely change a join order; errors of 10Ã are what turn a 90 ms query into an 8 second one.
Rows Removed by Filter: 750000is the real trade-off the planner weighed: a sequential scan reads every page once and discards three quarters of the tuples, while an index scan would touch 250,000 scattered heap pages, each charged atrandom_page_cost.- The first cost figure is startup cost â the price of producing the very first row. A plan with a high startup cost and a modest total cost is ideal for a report that reads every row, and poor for a paginated
LIMIT 10endpoint. - Planning at 0.234 ms against execution at 89.567 ms is healthy. Once execution drops under a millisecond, planning dominates the request and a cached prepared statement becomes the lever that matters.
loops=1on every node means each node ran once. A node showingloops=48processed its input 48 times, so its effective cost is 48 times the per-loop figure shown in the line.
Statistics and Histograms
-- View table statistics
SELECT
attname,
null_frac,
avg_width,
n_distinct,
correlation,
most_common_vals,
most_common_freqs,
histogram_bounds
FROM pg_stats
WHERE tablename = 'orders'
AND attname = 'region';
-- Manually update statistics
ANALYZE orders;
-- Check statistics target
SELECT
attname,
attstattarget,
pg_stats.ext_stats
FROM pg_attribute
JOIN pg_stats ON attname = attname
WHERE attrelid = 'orders'::regclass;
Histogram Representation:
For a column with values :
Each bucket contains approximately values.
The columns exposed through pg_stats each answer a different question, and the planner reads all of them before it commits to a plan:
null_fracis the share of rows that are NULL. An equality predicate is estimated as(1 - null_frac)scaled by the histogram fraction, so a column that is 90% NULL makescolumn = 'x'look far more selective than a casual glance at the data suggests.n_distinctcounts distinct values. A positive number is an absolute count, a negative number is a fraction of the row count, so-0.01means one distinct value per hundred rows. For astatuscolumn with four values the planner derives 0.25 selectivity per value from this number alone, without touching the histogram.avg_widthis the average byte width of the column. It feeds thewidth=estimate printed on every EXPLAIN node and decides whether an in-memory sort is plausible under the currentwork_mem.correlationis the Pearson correlation between physical row order and logical value order. Values near 1.0 or -1.0 mean an index scan reads the heap almost sequentially; values near 0 mean every index lookup is a genuinely random 8 KB page fetch, which is exactly whatrandom_page_cost = 4.0charges for.histogram_boundsis a sorted sample of at mostdefault_statistics_targetvalues (100 by default) that converts a range predicate into a fraction of the table. Values that appear more often than the histogram resolution can land inmost_common_valsinstead, which is why the two lists must be read together.
ANALYZE never reads the whole table. It samples up to 30000 Ã statistics_target rows per column â three million rows at the default target of 100 â and extrapolates the rest. When a range predicate keeps being estimated wrong on a single skewed column, raising the target for that column only is the cheapest repair available:
-- Spend more analyzer time on one hard column, not the whole table
ALTER TABLE orders ALTER COLUMN total_amount SET STATISTICS 1000;
ANALYZE orders;
-- Create custom statistics for better estimates
CREATE STATISTICS orders_region_status (region, status) ON orders;
-- Check correlation statistics
SELECT
correlation,
-- Physical correlation affects index scan cost
CASE
WHEN correlation > 0.8 THEN 'High correlation - index scan efficient'
WHEN correlation > 0.5 THEN 'Medium correlation'
ELSE 'Low correlation - index scan less efficient'
END AS analysis
FROM pg_stats
WHERE tablename = 'orders'
AND attname = 'order_date';
Cost Calculation Formulas
Sequential Scan Cost:
Index Scan Cost:
Hash Join Cost:
Merge Join Cost:
-- Compare different join strategies
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.*, c.*
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date > '2024-01-01';
-- Force specific join method
SET enable_hashjoin = off;
SET enable_mergejoin = off;
-- Only nested loop remains
-- Reset
RESET enable_hashjoin;
RESET enable_mergejoin;
The plan that comes back is a direct consequence of the input sizes, and the arithmetic is easy to follow with the sample data. orders holds 1,000,000 rows and customers holds 10,000, so a hash join builds its hash table on the customers side: 10,000 rows at roughly 40 bytes of key material is about 400 KB, well inside the 4 MB default work_mem. The build phase therefore finishes in a single batch and the probe phase streams the million order rows through it.
Raise the build side to 500,000 rows and the same hash table wants roughly 20 MB. It no longer fits, so the executor spills to disk and the plan reports Batches: 2 or higher, with every additional batch re-reading the probe side. A batch count above 1 is the clearest signal you can get that work_mem is undersized for that query. A merge join then becomes competitive: it must sort both inputs first, but each input is read exactly once afterwards, and the plan shows a Sort node above each side instead of a Hash node.
A nested loop is correct only when the outer side is tiny or the inner side has a cheap index. Probing 10,000 customers against an index on orders(customer_id) costs 10,000 index traversals and is unremarkable. Reverse the sides and probe 1,000,000 times and the same plan shape performs a million traversals, three to four page reads each â the classic way a join-order flip turns a 90 ms query into a 12 second one after a data change. This is the first thing to check when a query regresses: not the algorithm, but which relation ended up on the inner side.
Index Selection Algorithm
The optimizer selects indexes based on:
-- Create various indexes for comparison
CREATE INDEX idx_orders_region ON orders(region);
CREATE INDEX idx_orders_date ON orders(order_date);
CREATE INDEX idx_orders_composite ON orders(region, order_date, total_amount);
CREATE INDEX idx_orders_partial ON orders(total_amount) WHERE status = 'shipped';
-- Compare plans with different indexes
EXPLAIN SELECT * FROM orders WHERE region = 'North' AND order_date > '2024-06-01';
-- Drop indexes to see plan changes
DROP INDEX idx_orders_region;
EXPLAIN SELECT * FROM orders WHERE region = 'North' AND order_date > '2024-06-01';
Index Cost Comparison:
| Index Type | Random I/O | Sequential I/O | Memory |
|---|---|---|---|
| Seq Scan | 0 | High | Low |
| B-Tree | Medium | Low | Medium |
| Hash | Low | Low | High |
| GiST | High | Low | Medium |
â ī¸
Index Overhead: Each index adds write overhead. The optimizer must balance read performance vs write cost. Monitor index usage with pg_stat_user_indexes.
Advanced Cost Estimation
Correlation Factor:
Selectivity Estimation:
-- Analyze selectivity of different predicates
EXPLAIN SELECT * FROM orders
WHERE total_amount BETWEEN 1000 AND 5000;
EXPLAIN SELECT * FROM orders
WHERE total_amount > 1000;
EXPLAIN SELECT * FROM orders
WHERE status = 'shipped' AND region = 'North';
-- Check estimated vs actual for different ranges
EXPLAIN ANALYZE SELECT * FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-03-31';
EXPLAIN ANALYZE SELECT * FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31';
Query Plan Cache Analysis
-- Check plan cache statistics
SELECT
query,
calls,
total_time,
mean_time,
rows
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 10;
-- Analyze plan stability
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT * FROM orders WHERE region = 'North';
-- Compare with different parameter values
PREPARE test_query AS SELECT * FROM orders WHERE region = $1;
EXPLAIN ANALYZE EXECUTE test_query('North');
EXPLAIN ANALYZE EXECUTE test_query('South');
Custom plans against generic plans
That prepared statement exposes the planner's plan-cache policy. PostgreSQL builds a custom plan â one specialised for the actual parameter values â for the first five executions. From the sixth onward it estimates a generic plan built around the placeholder and compares the two: if the generic plan costs no more than the average cost of the five custom plans, it keeps the generic plan; otherwise it stays on custom plans for the life of the prepared statement.
This is why 'North' and 'South' behave so differently through the same statement. 'North' matches about 250,000 rows and 'South' about 40,000 in the sample data, so a single generic plan that picks a hash join for both is close to optimal for one and several times too slow for the other. If pg_stat_statements shows identical query text with mean_time varying by an order of magnitude, the repair is either plan_cache_mode = force_custom_plan for that session or rewriting the predicate so its shape does not change between runs.
Cardinality Errors and How to Repair Them
Most expensive plans are not bad algorithms; they are arithmetic mistakes made before execution starts. The classic mistake is assuming column independence. When a predicate constrains two columns, the planner multiplies their selectivities:
With region = 'North' at 0.25 and status = 'shipped' at 0.40 the product is 0.10, so 100,000 rows of a million are expected. If in reality seven in ten North orders are shipped, the true count is 175,000 and the join input is under-estimated by 75,000 rows â more than enough to justify a nested loop where a hash join was the right answer.
Extended statistics let the planner see the joint distribution instead of guessing:
-- Tell the planner these two columns move together
CREATE STATISTICS customers_region_credit (region, credit_limit) ON customers;
ANALYZE customers;
-- The estimate should now track the real distribution
EXPLAIN SELECT * FROM customers
WHERE region = 'North' AND credit_limit > 10000;
The symptoms show up the same way in every production database: a plan that flips between a hash join and a nested loop depending on the hour, rows=1 on a node that visibly returns thousands, or a sort spilling to disk because the estimate was a tenth of the real count. The recovery order is fixed â ANALYZE the table, add extended statistics on the correlated pair, raise statistics_target on the skewed column, and only then reach for SET enable_... as a temporary stopgap while the real fix ships.
Performance Tuning Checklist
- Statistics Freshness:
ANALYZEafter major data changes - Index Usage: Check
pg_stat_user_indexes - Join Order: Verify optimal join sequence
- Memory Settings: Adjust work_mem, shared_buffers
- Parallel Queries: Enable parallel workers for large scans
âšī¸
Pro Tip: Use EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) with tools like pganalyze or explain.dalibo.com for visual plan analysis.
Mathematical Model for Plan Selection
The optimizer uses a dynamic programming approach:
Where is the query and is a candidate plan.
For joins with tables:
With pruning and heuristics:
â ī¸
Cardinality Estimation Errors: The #1 cause of bad query plans. Monitor with pg_stat_statements and tune statistics targets for critical columns.
Common Mistakes
Reading EXPLAIN cost figures as if they were milliseconds
Fix: Costs are dimensionless units used to rank plans; switch to EXPLAIN ANALYZE when you need real durations
Trusting statistics right after a bulk COPY or a large DELETE
Fix: Run ANALYZE manually â autovacuum only reanalyses once the modified-row threshold for that table is crossed
Multiplying selectivities on columns that are correlated, then blaming the join algorithm
Fix: Create extended statistics with CREATE STATISTICS on the column pair, re-run ANALYZE, and re-check the estimate before changing the query
Key Takeaways
- Total cost is I/O plus CPU plus network, and every page and tuple constant behind it is a GUC that can be tuned for the storage in front of you
- Startup cost governs paginated queries while total cost governs full scans; planning time only matters once execution time falls below a millisecond
- ANALYZE samples at most 30,000 rows times the statistics target, so a skewed column needs its own raised statistics_target to estimate ranges correctly
- Extended statistics repair the column-independence assumption, and plan_cache_mode controls when a prepared statement may switch to a generic plan