Chapter 10 of 12
Course Progress0 of 12 completed (0%)

SQL & Relational Database Mastery · Chapter 10 · ~15 min · Advanced

Reading Execution Plans & Query Tuning: EXPLAIN Deep Dive

Profile queries with EXPLAIN and EXPLAIN ANALYZE, diagnose sequential scans and disk-spill sorts, and author sargable predicates.

  • Interpret EXPLAIN and EXPLAIN ANALYZE execution plan trees from first principles
  • Identify expensive operations: Sequential Scans, Spill-to-Disk Sorts, and Hash Joins
  • Diagnose cardinality estimation errors caused by stale database statistics
  • Optimize slow queries through index seeks, sargable predicates, and join restructuring

Reading Execution Plans & Query Tuning: learn it visually

Profile queries with EXPLAIN and EXPLAIN ANALYZE, diagnose sequential scans and disk-spill sorts, and author sargable predicates.

Reading Execution Plans & Query TuningProfile queries with EXPLAIN and EXPLAIN ANALYZE, diagnose sequential scans and disk-spill sorts, and author sargable predicates.UNDERSTANDReading ExecutionPlansFOLLOW THE FLOWQuery TuningAPPLY ITProfile queriesEXPLAINReading Execution Plans & Query TuningProfile queries with EXPLAIN and EXPLAIN ANALYZE, diagnose sequential scans and disk-spill sorts, and author sargable predicates.UNDERSTANDReading ExecutionPlansFOLLOW THE FLOWQuery TuningAPPLY ITProfile queriesEXPLAIN

1Intuition: The Cost-Based Optimizer (CBO)

SQL is a declarative language: you specify what data you want, not how to retrieve it. Under the hood, the Cost-Based Optimizer (CBO) evaluates dozens of candidate execution trees, assigning a cost to each based on table statistics (row counts, null fractions, distinct values, and histograms).

Understanding how to inspect these execution trees with EXPLAIN is the definitive skill separating junior developers from senior database engineers.

Cost Units

Relative to single sequential page fetches (1.0). Random page reads are weighted higher (4.0 in spinning disks, 1.1 in NVMe SSDs).

Actual Time vs Cost

Cost is an estimate; actual time in EXPLAIN ANALYZE shows true wall-clock startup and completion times in milliseconds.

Buffers & Cache

Adding (BUFFERS) to EXPLAIN ANALYZE reveals whether pages were served from RAM buffer cache (hit) or read from disk (read).

Concept Check

What does the term 'Sargable' (Search ARGument ABLE) mean in relational database query optimization?

2Architecture: Execution Plan Nodes & Tuning Antipatterns

Execution trees are read inside-out and bottom-up: leaf operations execute first and stream their output rows up into parent nodes. Explore the 3 crucial execution models below:

Wrong idea: EXPLAIN cost=450.25 represents 450 milliseconds of runtime

cost=450.25 → Assumed: 450ms elapsed time
❌ Unitless Score: Query hasn't even run; hardware latency is unknown

Assuming cost numbers reflect real elapsed time on a clock. The cost metric is an arbitrary unitless mathematical score based on estimated disk block fetches and CPU operation weights without executing the query.

Real system: EXPLAIN evaluates statistics; EXPLAIN ANALYZE physically runs queries

EXPLAIN ANALYZE → actual time=0.18ms, rows=42, buffers=4
✅ Empirical Reality: Reveals true bottlenecks and cardinality mismatches

EXPLAIN prints the optimizer's mathematical hypothesis. EXPLAIN ANALYZE physically executes the query against real data, measuring true wall-clock time, actual row counts, and memory buffer hits.

-- Production Query Profiling Pattern:
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS)
SELECT
    o.order_id,
    c.customer_name,
    o.total_amount
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE o.order_date >= '2026-01-01'
  AND o.order_date < '2027-01-01'
  AND o.status = 'paid'
ORDER BY o.total_amount DESC
LIMIT 50;
Concept Check

In an EXPLAIN ANALYZE output, you notice: 'Seq Scan on users (cost=0.00..1845.00 rows=10 width=45) (actual time=0.08..412.10 rows=850000 loops=1)'. What critical issue does this reveal?

3Interactive Visual: The Execution Plan Tree Inspector

Compare the execution tree of a slow, non-sargable query against its tuned equivalent. Inspect the cost multipliers, memory spills, and disk I/O metrics in real time.

Interactive EXPLAIN ANALYZE Execution Tree Inspector

Total Elapsed Time
284.15 ms
1,578x slower
Planner Cost Unit
48,250.00
Synthetic optimizer score
Disk I/O Scanned
32,000 Pages
256 MB disk read
Memory Sort Method
External Disk
Spilled 48MB to disk
• Hash Join (cost=1200.00..48250.00 rows=2500 width=128)284.15 ms
Hash Cond: (orders.customer_id = customers.id)
• Seq Scan on orders (cost=0.00..32000.00 rows=2500000)
Filter: (UPPER(country) = 'CA' AND EXTRACT(YEAR FROM order_date) = 2026)
⚠️ Non-Sargable Predicate: UPPER() and EXTRACT() force engine to evaluate 2.5 million rows sequentially!
• Sort (Sort Method: external merge Disk: 48,120kB)
⚠️ work_mem Exceeded: Sort dataset exceeded RAM allocation, spilling 48 MB of temporary files to SSD.
Concept Check

What does 'Sort Method: external merge Disk: 34120kB' in EXPLAIN ANALYZE signify?

4Bug Hunt: Eliminate Non-Sargable Predicates & SELECT *

A slow batch reporting query is pegging database CPU at 99%. Profiling shows that UPPER(country) = 'CA' and EXTRACT(YEAR FROM order_date) = 2026 are forcing a sequential scan on 2.5 million rows, while SELECT * transfers huge payloads across the network. Refactor the query to make it sargable.

SQL Bug Hunt · Query Tuning & Sargable Refactor
SQL

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?

• Replace UPPER(country) = 'CA' with country = 'CA'

• Replace EXTRACT(YEAR FROM ...) with order_date >= '2026-01-01' AND order_date < '2027-01-01'

• Replace SELECT * with explicit columns (e.g. order_id, order_date, total_amount)

Concept Check

Why might the database optimizer intentionally choose a Sequential Table Scan over an existing B-Tree index on a table with 1,000,000 rows?

5Recap & Query Tuning Checklist

  • Sargability First: Never wrap indexed columns in functions. Transform literal values instead of database fields.
  • Inspect Cardinality Discrepancies: If estimated rows and actual rows differ by an order of magnitude, run ANALYZE to refresh planner statistics.
  • Watch for Disk Spills: Look for "external merge Disk" in sorts and hash joins. Increase work_mem for analytical sessions to keep sorts in RAM.
  • Avoid SELECT *: Unnecessary columns force table heap lookups and disable high-speed Index-Only Scans.

Ready for Chapter 11 (Transactions, ACID & Locking)? Mark as complete:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us