# Topic 43: Query Optimization
EXPLAIN, EXPLAIN ANALYZE, Cost-Based Optimizer (CBO) decisions, sequential vs index scans, and buffer cache metrics.
1. Definition
Query Optimization is the internal database process where the Cost-Based Optimizer (CBO) analyzes table statistics and evaluates candidate execution plans to execute a query with minimal I/O and CPU cost.
2. Explain Like I'm 5
Query optimization is GPS navigation for your database: given traffic, roadblocks, and highway speeds (indexes and statistics), it calculates the fastest route before the car even starts moving.
3. Animation & Visual Simulation
Interactive Engine TraceQuery Optimization Visual Simulator
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, o.total
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE c.country = 'US';Active InputStep 1: Input & Parsing Stage
Initiating Query Optimization
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Diagnosing an API endpoint query that suddenly slowed down from 5ms to 800ms.
| Plan Node | When Used | Relative Cost |
|---|---|---|
| Seq Scan | Large percentage of table or unindexed column | High (Reads all disk pages) |
| Index Scan | Selective filter lookup (few rows) | Very Fast (B-Tree traversal + heap fetch) |
| Index-Only Scan | All projected columns exist inside index leaves | Fastest (Zero heap lookups) |
| Bitmap Index Scan | Combines multiple index filters into bitmask | Fast for medium selectivity |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectEXPLAIN SELECT * FROM orders WHERE user_id = 942;
EXPLAIN (ANALYZE, BUFFERS, TIMING) SELECT id, total_amount FROM orders WHERE user_id = 942 AND status = 'completed';
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Cost Formula | Cost = (Disk Pages * seq_page_cost) + (CPU Tuples * cpu_tuple_cost). |
| ANALYZE Caution | EXPLAIN ANALYZE actually executes the query! If you run it on DELETE or UPDATE, data will be modified! |
| Catalog Statistics | The optimizer relies on pg_statistic (refreshed by ANALYZE) to estimate row selectivity. |
| Cost formula components | CBO Cost = (pages * seq_page_cost) + (random_pages * random_page_cost) + (tuples * cpu_tuple_cost). |
| Four primary scan types | Sequential Scan (full heap), Index Scan (index + heap), Index-Only Scan (leaves only), and Bitmap Index Scan. |
7. Deep Dive: Reading an EXPLAIN ANALYZE Plan: Cost, Rows, Buffers
A plan line like: "Index Scan using idx_orders on orders (cost=0.42..8.45 rows=2 width=32)" indicates: 1) startup cost: 0.42, 2) total estimated cost: 8.45, 3) estimated matching rows: 2. Buffers: shared hit=3 means 3 pages were read directly from RAM buffer pool.
Index Scan using idx_orders_user_id on orders (cost=0.42..8.45 rows=2 width=32) (actual time=0.040..0.042 rows=2 loops=1) Index Cond: (user_id = 942) Buffers: shared hit=3 read=1
8. Advantages & Disadvantages
Advantages
- •Gives full transparency into database execution choices.
- •Enables targeted indexing and performance tuning.
Disadvantages & Trade-offs
- •Interpreting complex 50-node query execution trees requires deep storage engine knowledge.
9. Common Interview Questions
Q1.How do you read and interpret an "EXPLAIN (ANALYZE, BUFFERS)" execution plan in PostgreSQL?
1. Cost (e.g. cost=0.42..8.45 rows=2 width=32): 0.42 is the startup cost before the first row is emitted; 8.45 is total cost; rows is optimizer estimate; width is average byte size per tuple. 2. Actual Time: real wall-clock execution time in milliseconds. 3. Buffers: shared hit=3 (pages found in RAM cache) vs read=1 (pages fetched from physical disk). High disk reads indicate I/O bottlenecks.
Q2.What are the four primary table scan mechanisms used by the query optimizer?
1. Sequential Scan: reads all 8 KB pages sequentially; optimal for full table exports or tables < 100 pages. 2. Index Scan: traverses B-Tree to find leaf pointers, then fetches corresponding tuples from heap pages one by one. 3. Index-Only Scan: satisfies query entirely from B-Tree leaf payload without touching heap pages. 4. Bitmap Index Scan: scans index, builds a bitmap of matching heap page block IDs in RAM, sorts them sequentially, and fetches heap pages in batch.
Q3.Why did the optimizer choose a Sequential Scan over my B-Tree index?
1. Low Selectivity: if a query matches > 15-20% of the table, sequential block reads are physically faster than random index seek + random heap fetches. 2. Small Table: if the table fits in 3 disk blocks, scanning all blocks takes less CPU than navigating a B-Tree. 3. Non-SARGable predicate: column was wrapped in a function or suffered implicit type casting. 4. Stale statistics: autovacuum has not updated pg_statistic.
Q4.What is the difference between Planning Time and Execution Time?
Planning Time is the time taken by the Cost-Based Optimizer to parse the AST, check statistics, enumerate join orders, evaluate costs, and pick the physical plan tree. Execution Time is the actual time taken by the storage engine to execute the plan operators, fetch disk blocks, and stream tuples.
Q5.What is Join Reordering and how does the optimizer prevent combinatorial explosion (GEQO)?
For a query joining N tables, there are (2N - 1)! / (N - 1)! possible join trees. For small joins (N < 12), the planner uses dynamic programming to test all valid join orders. When N exceeds from_collapse_limit or geqo_threshold, the planner switches to Genetic Query Optimization (GEQO), using heuristic evolutionary algorithms to find a near-optimal plan without exhausting CPU memory.
10. Interview-Ready Answer
“The Cost-Based Optimizer determines execution plans by evaluating estimated I/O and CPU costs against catalog statistics. EXPLAIN ANALYZE provides empirical profiling data, showing actual execution time, scan nodes, and buffer pool hits.”
11. Quick Test
What is the danger of running "EXPLAIN ANALYZE DELETE FROM sessions WHERE expired = true;" in production?