Query Optimization & EXPLAIN Plans

Difficulty
Importance

The problem

When a query is slow, guessing at the cause wastes time — a query planner exposes exactly how it intends to execute a query, and reading that plan turns 'this feels slow' into a precise diagnosis of which step is actually expensive.

Why now

Joins and query planning introduced how the planner chooses a strategy; this topic is the applied skill of reading that choice back out and fixing it when it's wrong, closing the loop between complexity analysis's general 'count the cost' method and this specific, real-world tool for doing exactly that on live queries.

Mental model

EXPLAIN prints the plan the database intends to follow — which index (if any) it'll use, which join strategy, and an estimated cost for each step. Reading a plan is complexity analysis in reverse: instead of deriving Big-O from code you wrote, you're reading the actual execution strategy the database chose and judging whether it's the cheap one available.

Requires

Unlocks

Used in

Projects

  • Take a genuinely slow query, run EXPLAIN ANALYZE, identify the most expensive step, and fix it (add an index, rewrite the query, or both)
  • Compare EXPLAIN output for the same query before and after adding a relevant index, explaining the change in chosen strategy

Examples

  • An EXPLAIN showing 'Seq Scan' on a large table where an index exists on the filtered column is a strong signal something is wrong — either a missing index or a query that can't use the one that exists
  • Reordering a JOIN or rewriting a subquery as a JOIN can change the plan's estimated cost dramatically, even though the result is identical

Resources

Mastery checklist