Skip to content

Lesson 6 of 9 · 26m

Query Planning and Statistics

The planner is a cost model fed by imperfect statistics. When it chooses badly, your job is to inspect the estimate-versus-reality gap before rewriting SQL at random.

SQL is declarative, which means the database has to invent an execution strategy. The query planner estimates row counts and costs, chooses join order, picks scans, and decides whether to sort, hash, or use an index. When the estimates are wrong, the plan is wrong — even if the SQL is elegant.

Read the plan backwards

EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '7 days'
ORDER BY o.created_at DESC
LIMIT 50;

A PostgreSQL plan is a tree. Data starts at the leaves — scans — and flows upward through filters, joins, sorts, and limits. Compare rows estimates with actual rows at every node. The first huge divergence is usually the root cause.

The basic scan choices

  • Sequential scan: read the table in order; good when a large fraction of rows match.
  • Index scan: traverse an index, then fetch rows; good for selective predicates and small limits.
  • Bitmap heap scan: collect many row locations from an index, sort them, then fetch pages; middle ground for moderately selective queries.
  • Index-only scan: answer entirely from the index when visibility information permits.

People often ask why a database "refuses to use the index." Usually because using it would be slower. If a predicate matches 60% of a table, random page fetching through an index is worse than reading the table sequentially.

Joins are algorithmic choices

nested loop:   for each outer row, probe inner rows
hash join:     build hash table on one input, probe with the other
merge join:    sort both sides, then walk them together

Nested loops are excellent with tiny outer inputs and indexed inner lookups. Hash joins shine for large unordered inputs. Merge joins help when inputs are already sorted. A planner forced into nested loops across millions of rows is often suffering from a bad row-count estimate, not a bad join implementation.

Statistics are samples, not truth

PostgreSQL's planner uses histograms, most-common values, and distinct counts gathered by ANALYZE. Correlated columns defeat simple independence assumptions:

CREATE STATISTICS city_state_stats (dependencies, ndistinct)
ON city, state FROM addresses;
ANALYZE addresses;

Without extended statistics, city='Paris' AND state='Texas' may be estimated as much rarer than it is, because the planner assumes the predicates are independent.

Field notes

  • Use EXPLAIN ANALYZE on a copy of production data when possible; plans are data-dependent.
  • Watch Buffers: shared hit versus read; cache hits can make a bad test plan look good.
  • Functions around indexed columns (lower(email) = ...) defeat normal indexes unless a matching expression index exists.
  • Parameterized queries can produce different plans because the planner may or may not know the actual value.
  • Do not cargo-cult optimizer hints. Fix statistics, indexing, and query shape first; hints are operational debt.

Was this lesson helpful?

Sign in to rate