DatabasesDeeper

Kayavak / Databases / DB·60 Query Optimisation / Deeper

Deeper · Databases

Query Optimisation

The questions the chapter doesn't stop for: why this exists, the model to keep in your head, what changes when an assumption does, how sure we are of each claim, and what's still open. Read it after the chapter; back to the chapter.

Why does this exist?

A declarative language only works if something turns "what" into a fast "how". In 1979 Patricia Selinger and colleagues at IBM published how System R did it: estimate the cost of alternative plans from statistics about the data, and use dynamic programming to search join orders efficiently. Nearly every relational optimiser since descends from that paper. It made SQL practical: a good plan and a bad plan for the same query can differ by factors of thousands.

The weak point has always been estimation. Optimisers guess how many rows each step produces, usually assuming columns are independent and values evenly spread, and errors multiply through joins. A 2015 study (How Good Are Query Optimizers, Really?, Leis and others) found cardinality estimates in real systems often off by orders of magnitude, and that those errors, more than cost models, cause bad plans.

The mental model

Try it yourself first: write your own model in the Mental Model Explorer, then compare.

The planner estimates how many rows each step will produce and picks the plan it thinks is cheapest. Bad plans almost always come from bad estimates, so read EXPLAIN ANALYZE by comparing estimated rows with actual rows.

Question Answer
What is it? The database component that chooses how to execute a query
Problem it solves Fast execution of declarative queries without the user choosing algorithms
Parts Statistics, selectivity and cardinality estimates, access paths (scans, indexes), join methods (nested loop, hash, merge), join order search, a cost model
How it works Enumerate plans, estimate each step's rows and cost, keep the cheapest; execute it
Assumptions Statistics are fresh; columns are independent; values are uniformly distributed within histogram buckets
When they change Correlated columns (city and postcode) make the planner underestimate, so it picks nested loops over millions of rows
Where it fails Many-table joins, skewed data, parameterised queries whose best plan depends on the values
Related ideas Algorithms and complexity (Foundations, ch04); indexes and B-trees (ch58); performance method (The Backend, ch41)

What if?

What if the planner thinks a filter keeps 10 rows when it keeps 100,000?

Reason it through, then open

It will choose plans that are cheap for 10 rows: a nested loop that looks up each row in another table by index. With 100,000 rows that's 100,000 index lookups instead of one hash join, and the query that "should" take milliseconds takes minutes. Fixing the estimate (fresh statistics, extended statistics on correlated columns) usually fixes the plan without touching the query.

What if you add an index for every query?

Reason it through, then open

Reads get faster, and every insert, update and delete must now update every index: writes slow down, storage grows, and the planner has more options to choose wrongly between. Indexes that are never used still cost on every write. Add indexes for measured needs and remove unused ones.

Where the boundary is

Aspect Nested loop join Hash join
Best when The outer side is small and the inner side has an index Both sides are large, joined on equality
Cost grows with Outer rows × lookup cost Size of both inputs (linear)
Bad when The outer side is much larger than estimated The hash table doesn't fit in memory

Derive it

Why the optimiser can't try every join order, and how it copes.

  1. Joining n tables one at a time in a chain (a left-deep plan) can be done in n! orders: 5 tables give 120, 10 give 3,628,800, 15 give over a trillion.
  2. Trying them all is impossible beyond a handful of tables. Selinger's insight: the best plan for joining a set S of tables doesn't depend on how you'll use the result later (apart from its sort order).
  3. So compute the best plan for every subset of tables, building larger subsets from smaller ones: dynamic programming. There are 2ⁿ subsets, not n! orders: 1,024 for 10 tables.
  4. Even 2ⁿ grows too fast eventually, so PostgreSQL switches to a randomised genetic search above a threshold (12 tables by default).
  5. The search is exact only given the estimates: a perfect search over wrong cardinalities still finds a wrong plan.

How sure are we?

Claim How it's known Where from
Cost-based optimisation with dynamic programming Historical Selinger et al., SIGMOD 1979
Cardinality errors cause most bad plans Measured Leis et al., VLDB 2015
Left-deep join orders number n! Theorem Counting permutations
PostgreSQL's genetic optimiser threshold is 12 Convention geqo_threshold default; configurable

Still open

Learned optimisers and learned cardinality estimators (2018 onwards) are a very active research area; whether they beat classic optimisers robustly in production is not yet settled.

What would change your mind? If a plan were bad even though estimated and actual rows matched, the cost model, not estimation, would be at fault. That happens, but less often.

Recall

What usually causes a bad query plan?

Wrong cardinality estimates, from stale statistics, correlated columns or skew.

How do you diagnose one?

Compare estimated and actual rows at each step of EXPLAIN ANALYZE.

Why does dynamic programming make join ordering feasible?

It considers 2ⁿ subsets instead of n! orders, reusing the best plan for each subset.

When is a nested loop join a bad choice?

When the outer side has far more rows than estimated.

Reflect

Be honest with yourself; this stays in your browser. Anything you can't tick yet is what to revisit.