Course map

Topic 066 / Core

Query execution and optimization

Chapter 5.3 · Indexing, Search, and Query Performance

What and why

The same SQL statement can be executed many different ways — scan or index, which join algorithm, which order — and the engine's optimizer picks one based on estimated cost. Reading that plan, not guessing, is how a slow query gets diagnosed. Builds on: → 64 (indexing).

Diagram

EXPLAIN ANALYZE SELECT …
  └─ Hash Join  (cost=…, rows=…)
      ├─ Seq Scan on "order"      (cost=…, rows=1,000,000)  ← expensive
      └─ Index Scan on customer   (cost=…, rows=1)

How it works

  1. The parser turns SQL into a logical plan: what tables, filters, joins, aggregates.
  2. The optimizer considers physical plans (sequential vs. index scan; nested loop, hash, or merge join) using table statistics (row counts, value distributions).
  3. It picks the plan with the lowest estimated cost.
  4. EXPLAIN ANALYZE shows both estimated and actual rows per step — a large gap between them means stale statistics are misleading the optimizer.
  5. Fix the most expensive node first (usually a sequential scan with a large row count or a bad join order), then re-measure.

Practical example

(numbers illustrative). A query filtering "order" by customer_id with no index shows Seq Scan … rows=1,000,000 and a multi-second runtime; after adding the index from topic 64, the plan changes to Index Scan … rows=12 and the runtime drops to milliseconds — the plan itself proves the fix, not just the clock.

When to use it

  • Use when: before touching any slow query — read the plan first.
  • Avoid when: guessing at a new index or a query rewrite before confirming, via EXPLAIN, what the engine is actually doing.
  • Failure scenarios: stale statistics after a large bulk load silently picking a bad plan (running ANALYZE refreshes them); a query that performs fine on a small development dataset and collapses in production because the optimizer chooses a different plan at real row counts.
  • Simpler alternative: often a query rewrite (filter earlier, avoid SELECT *, avoid a function wrapped around an indexed column) fixes it before any new index is needed.

Practice

(numeric/mechanism, 20–30 min, lab Postgres — merges this chapter's slow-query exercise). Load a table with a large synthetic row count (10 million rows is the reference scale; a smaller count in the lab is fine if it still forces a sequential scan), find a query that is slow against it, run EXPLAIN ANALYZE, identify the most expensive node, add the index from topic 64 that targets it, and re-run. Done when the plan changes from a sequential to an index scan and the measured time drops.

Shared lab setup

Key takeaway

Read the plan before changing anything; fix the most expensive node, then re-measure. Done when you can: read an EXPLAIN ANALYZE output and name the single most expensive step. Used next in → 67 (the storage engine these scans run against).

References

None — this topic makes no external claims.

Source directory

Search the guide