Skip to content
Back to 50 Concepts
Topic 43 of 50indexingAdvanced

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Query Optimization Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Query Optimization
SQL Input

Initiating Query Optimization

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 GPS Navigation: Calculating route times based on road types (indexes vs table scans) before committing to driving the vehicle.

4. Real-World Example

Diagnosing an API endpoint query that suddenly slowed down from 5ms to 800ms.

EXPLAIN Scan Types
Plan NodeWhen UsedRelative Cost
Seq ScanLarge percentage of table or unindexed columnHigh (Reads all disk pages)
Index ScanSelective filter lookup (few rows)Very Fast (B-Tree traversal + heap fetch)
Index-Only ScanAll projected columns exist inside index leavesFastest (Zero heap lookups)
Bitmap Index ScanCombines multiple index filters into bitmaskFast for medium selectivity
Relational walkthrough: Running EXPLAIN ANALYZE reveals whether the engine is using an index or scanning raw disk pages.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Inspect query plan without executing
EXPLAIN
SELECT * FROM orders WHERE user_id = 942;
Shows estimated cost, row counts, and plan tree without running the query.
Step 2: Real execution with timings and buffer stats
EXPLAIN (ANALYZE, BUFFERS, TIMING)
SELECT id, total_amount
FROM orders
WHERE user_id = 942 AND status = 'completed';
ANALYZE executes the query, reporting real wall-clock execution time and buffer cache hits.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Cost FormulaCost = (Disk Pages * seq_page_cost) + (CPU Tuples * cpu_tuple_cost).
ANALYZE CautionEXPLAIN ANALYZE actually executes the query! If you run it on DELETE or UPDATE, data will be modified!
Catalog StatisticsThe optimizer relies on pg_statistic (refreshed by ANALYZE) to estimate row selectivity.
Cost formula componentsCBO Cost = (pages * seq_page_cost) + (random_pages * random_page_cost) + (tuples * cpu_tuple_cost).
Four primary scan typesSequential 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
Caution: If estimated rows differ from actual rows by an order of magnitude (e.g. est=1 vs act=10,000), run ANALYZE to refresh table statistics.

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

Scenario Question:

What is the danger of running "EXPLAIN ANALYZE DELETE FROM sessions WHERE expired = true;" in production?

Select your answer: