Query Optimization & Execution Plans (EXPLAIN ANALYZE)
Interpret database execution plans: Cost-Based Optimizer (CBO) statistics, Seq Scan vs Index Scan vs Index-Only Scan, WorkMem spills, and query tuning.
01.1. What is the Cost-Based Optimizer (CBO)?
Relational databases use a Cost-Based Optimizer (CBO) to determine the physical execution plan for every SQL query. Unlike procedural code where you write explicit loops, declarative SQL specifies what data you want, leaving how to retrieve it to the CBO.
The optimizer calculates arbitrary cost units (where 1.0 unit = 1 sequential 8KB page read from disk):
Total Cost = (Disk Page Reads Γ Page Cost) + (Rows Processed Γ CPU Tuple Cost) + (Operator Cost)
How Statistics Guide the CBO:
The database maintains statistical histograms in its system catalog (e.g., pg_statistic in PostgreSQL, mysql.innodb_table_stats):
- Number of distinct values (
n_distinct): Measures column cardinality. - Most Common Values (MCVs): Tracks frequency distribution of popular values.
- Null Fraction: Percentage of rows containing
NULL.
If statistics become stale (e.g., after loading 10M rows without running ANALYZE), the CBO makes catastrophic routing errors (e.g., choosing a Sequential Scan on 10 million rows instead of an Index Scan).
Query Parsing, Cost-Based Optimizer (CBO), and Execution Plan Tree π
Query Parsing, Cost-Based Optimizer (CBO), and Execution Plan Tree π
How a declarative SQL query is evaluated against data statistics (pg_statistic) by the Cost-Based Optimizer to choose the lowest-cost physical execution plan.
Unlock Topic #47: Query Optimization & Execution Plans (EXPLAIN ANALYZE)
You are viewing a preview. The full in-depth engineering deep dive, interactive simulators, architecture flowcharts, and self-assessment quizzes for this topic are available with Pro or Lifetime Access.
Failure modes, high-throughput bottlenecks, and real FAANG implementation decisions.
Interactive system topology diagrams, live parameter simulators, and downloadable SVG charts.
Staff-level multiple-choice quiz questions with instant feedback and answer explanations.
Firebase Google authentication automatically syncs your completed topics and quiz scores.
How clear and staff-actionable was this system breakdown?