Cost-Based Query Optimization
Trace cost-based join enumeration, interesting orders, and a correlation error that changes the optimizer’s estimate by a factor of one hundred.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 3
- Reading time
- 2 min
In this article3 chapters
What a dynamic-programming entry represents
For a fixed set of relation instances, a cost-based optimizer searches through equivalent logical plans and physical implementations. In a simplified left-deep search, let \(B(S)\) be the minimum cost for a subset \(S\), and let \(J(T,R)\) be the additional cost of joining the partial result for \(T\) to a relation \(R\). If the output property and estimated size of each partial result are fixed, the recurrence is
\[ B(S)=\min_{R\in S}\bigl[B(S\setminus\{R\})+J(S\setminus\{R\},R)\bigr], \quad |S|>1. \]
In an actual optimizer, plans for the same subset can differ in sort order, partitioning or parameterization. A locally more expensive sorted plan can save a later sort or enable a merge join. Keep separate entries for properties that affect future cost. The Selinger approach calls useful output orders “interesting orders”.
Selectivity under correlation shows why independent column statistics can miss intermediate cardinality by a large factor. Execution-plan inspection lets a reader locate the first operator where that error appears.
A correlation error that changes a plan
Suppose columns \(A,B\) always agree and the common value is uniform over one hundred possibilities. Each individual filter \(A=7\) or \(B=7\) keeps one row in a hundred in expectation. Multiplying these selectivities predicts that their conjunction keeps one in ten thousand. In fact it still keeps one in a hundred. On a million rows the estimate is one hundred rows and the expected result is ten thousand. This error can make indexed nested loops look cheaper than a hash join.
Where search and estimation interact
Multicolumn statistics can represent some dependencies and sampled feedback can diagnose estimation errors. Physical details still matter, including when a hash table spills and whether data are already partitioned. Worst-case optimal joins broaden the candidate set when intermediate binary joins are the obstacle. Learned indexes change the cost of selected range access paths. Measure plan estimates at intermediate operators since a plausible final row count can conceal cancelling errors.[1][2]