Query optimisation and evaluation plans
Clear, exam-focused notes on query optimisation and evaluation plans: logical vs physical plans, cost models, join algorithms, join-order optimisation (Selinger DP), and worked cost examples with step-by-step calculations.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Query optimisation decides how a DBMS converts a SQL query into an efficient sequence of operations. Engineers use these techniques to lower I/O and response time when designing DB engines, writing tuned SQL, or choosing indexes and physical layouts.
Key ideas
Start with definitions.
- Query: a request for data from the database (for example a SELECT statement). I will use the SQL notation but explain each step.
- Logical plan: a tree of relational-algebra operators (selection σ, projection π, join ⋈, etc.) that expresses what the query computes, independent of how it is executed.
- Physical plan: a tree where each logical operator is implemented by a specific algorithm (for example, a join implemented by nested-loop, sort-merge or hash join). A physical plan is executable.
- Query optimisation: the process that maps a logical plan to a low-cost physical plan using equivalences, cost estimation and search.
- Cost model: a model that assigns a numeric cost to plans (typically dominated by disk I/O) so the optimiser can compare plans.
- Selectivity: fraction of tuples that satisfy a predicate. If a relation has T tuples and after applying predicate p it has T' tuples, selectivity s = T'/T.
- Cardinality: number of tuples (rows) in a relation or intermediate result.
- Access path: how a base relation is read—full table scan, index scan, clustered index range scan, etc.
- Join algorithms: implementations of join. Common ones: nested-loop join, block nested-loop join, index nested-loop join, sort-merge join, hash join. I define each when used below.
- Join-order problem: for n relations there are exponentially many join orders; the optimiser must search this space for a good order.
- Selinger-style dynamic programming (DP) optimiser: enumerates best plans for subsets of relations using a bottom-up DP; runs in O(n^2 · 2^n) time (and O(n · 2^n) space) and returns optimal left-deep plans under its cost model and assumptions.
- Heuristics vs cost-based optimisation: heuristics (push selections, push projections, join commutativity/associativity) provide safe rewrites; cost-based search picks between many equivalent logical plans using estimated costs.
Algebraic equivalences universities ask for and how to apply them:
- Commutativity of join: R ⋈ S = S ⋈ R (for inner joins; not generally valid for outer/semi/anti joins). Draw: two children labelled R and S under a join node; swap children.
- Associativity of join: (R ⋈ S) ⋈ T = R ⋈ (S ⋈ T) (for inner joins; does not hold for outer joins). Draw: two binary trees with different grouping of R,S,T, label internal join nodes.
- Selection pushdown: σ_{p}(R ⋈ S) = (σ_{p1}(R)) ⋈ S if predicate p references only R (p1 is same predicate). Proof (intuitive): selection that uses only attributes of R can be applied before the join without changing final tuples because join does not create or modify attributes of R. This equivalence holds for inner joins; it is not generally valid for outer joins.
Assumptions commonly used in cost estimation (expose to examiner): independence of predicates, uniform distribution of values, availability and correctness of table statistics (cardinality, number of pages, distinct-values per attribute). Mention when these assumptions fail (skew, correlated predicates)—optimiser errors follow.
Describe what to draw for exam diagrams:
- For a logical plan: draw a tree; leaf nodes are relation names, internal nodes labelled with algebraic operators (σ, π, ⋈), add selection conditions on σ nodes.
- For physical plans: same tree but label operators with algorithm names (e.g., Hash-Join, Block-Nested-Loop), and annotate estimated cardinalities and page costs on each node.
- For join-order examples: draw left-deep tree vs bushy tree for three relations and label order of pairwise joins.
Formulas
Each formula on its own line, followed by meanings and when it applies.
B(R) — number of pages of relation R. Unit: pages. Use when estimating I/O.
T(R) — number of tuples (rows) in relation R. Unit: tuples.
pp(R) — tuples per page in R. Unit: tuples/page.
T(R) = B(R) * pp(R) — relation cardinality from pages. Applies when tuples are evenly packed.
selectivity s = T_after / T_before — fraction of tuples kept by a predicate. Unit: dimensionless.
Result size of join (naive) = T(R) * T(S) * f — where f is a small join selectivity fraction estimated from statistics (dimensionless). For equi-joins on a=b, a common estimator is T(R ⋈ S on a=b) ≈ T(R) * T(S) / max(V(R,a), V(S,b)) assuming uniformity and independence (V(X,attr) = distinct values of attr in X).
Block nested-loop join I/O cost: C = B(outer) + ceil(B(outer) / (M-2)) * B(inner) — B(X) pages of X, M buffer pages available. Unit: pages. Applies to block nested-loop where M-2 pages used for outer-block buffering, 1 page for input, 1 for output.
Index nested-loop join I/O cost: C = B(outer) + T(outer) * cost_index_lookup — cost_index_lookup measured in pages per lookup; T(outer) is tuples in outer. Unit: pages.
Sort cost (external merge sort, high level): C_sort ≈ 2 * B(R) * number_of_passes — number_of_passes = 1 + ceil(log_{M-1}(ceil(B(R)/M))). Unit: pages. Use when sorting before sort-merge join.
Sort-merge join cost (when sorting needed): C = C_sort(R) + C_sort(S) + B(R) + B(S) — pages. Applies when neither input is pre-sorted and external sort used.
Grace hash-join (ideal) I/O cost ≈ 3 * (B(R) + B(S)) — pages; assumes one partitioning pass and one probe/build pass and that partitions fit in memory. Mark for verification when partitions spill.
DP complexity for join order (Selinger DP): time ≈ O(n^2 · 2^n) — n is number of relations (space ≈ O(n · 2^n)). Use when explaining scalability limits.
(Units: pages or tuples; if system measures time per page on I/O, convert pages to seconds by multiplying by I/O-time-per-page.)
Worked examples
Example 1 — numeric cost comparison for join order (block nested-loop). Given:
- B(R)=1000 pages, B(S)=100 pages, B(T)=500 pages.
- tuples per page pp = 100 for all relations, so T(R)=100000, T(S)=10000, T(T)=50000.
- buffer pages M = 52, so M-2 = 50 pages for outer-block.
- Assume S has a foreign-key to R (so joining S ⋈ R returns exactly T(S) tuples) and join result stored with same pp=100.
Plan A: compute (S ⋈ R) first, then ⋈ T. Step 1: cost(S ⋈ R) using block nested-loop with S as outer: Formula: C1 = B(S) + ceil(B(S)/(M-2)) * B(R) Numbers: C1 = 100 + ceil(100/50) * 1000 = 100 + 2 * 1000 = 2100 pages. Result size: T(S ⋈ R) = T(S) = 10000 tuples → pages = 10000 / 100 = 100 pages. Step 2: join result (100 pages) with T (500 pages), choose result as outer: C2 = 100 + ceil(100/50) * 500 = 100 + 2 * 500 = 1100 pages. Total I/O = C1 + C2 = 2100 + 1100 = 3200 pages. Bold final: 3200 pages.
Plan B: compute (R ⋈ T) first, then ⋈ S. Step 1: choose T (500) as outer and R (1000) inner (smaller outer reduces passes ideally): C1' = 500 + ceil(500/50) * 1000 = 500 + 10 * 1000 = 10,500 pages. Assume join result does not shrink much (no foreign-key); but even if it did, second join with S (100 pages) will be costly. So total I/O will exceed Plan A. Conclusion: Plan A (join small relation S first) is much cheaper: 3200 pages vs >10500 pages. The example shows why join order matters.
Example 2 — Selinger DP enumeration for three relations R,S,T using pairwise costs from example 1. Given pairwise join costs (from block nested-loop choosing best outer each time):
- cost(R⋈S)=2100 (as computed), cost(S⋈T)=1100, cost(R⋈T)=10500. DP steps:
- For singletons, best plans are leaves with cost 0 (reading base relation cost B(R) is accounted when used in join formulas above).
- For all pairs, pick best:
- {R,S}: best cost = 2100, best plan = (S ⋈ R).
- {S,T}: best cost = 1100, best plan = (S ⋈ T).
- {R,T}: best cost = 10500, best plan = (T ⋈ R) (or symmetric).
- For full set {R,S,T}, combine best pair + remaining relation:
- Combine {R,S} (cost 2100) with T: estimated cost to join (R⋈S) result pages 100 with T = 1100 → total 3200 (as Example 1).
- Combine {S,T} (1100) with R: assume S has a foreign key to T so T(S ⋈ T) = T(S) = 10000 tuples → pages = 100; cost to join 100 pages with R (1000 pages) using block nested-loop = 100 + ceil(100/50) * 1000 = 2100; total = 1100 + 2100 = 3200. DP picks the min = 3200 pages plan. This trace demonstrates the DP table entries and how the final plan is selected.
Common mistakes
- Assuming selectivities are multiplicative without declaring independence; this gives wrong cardinalities for correlated predicates.
- Confusing logical equivalence (safe) with physical cost (different algorithms change cost significantly).
- Ignoring materialization cost when intermediate results are written to disk.
- Not checking whether hash join partitions fit in memory—using the ideal 3*(B(R)+B(S)) blindly.
For your exam
Types of questions: definitions (explain terms), short notes (join algorithms, cost model), derivations (derive block nested-loop cost), numericals (compute costs with given B(R), M, selectivities), trace of Selinger DP, draw plan trees. What a full-marks answer includes:
- Clear definitions of terms used.
- Statement of assumptions (buffers M, pp, independence, available statistics).
- Step-by-step cost derivation with formulas used, numbers substituted, and final numeric answer with units (pages or seconds with conversion).
- Correct diagrams: logical and physical plan trees annotated with costs/cardinalities.
- Short explanation of why one plan is better (intuitively: smaller intermediate result, fewer passes).
Quick check
- What is an access path? 2. Write the block nested-loop join cost formula and explain M. 3. State one assumption the optimiser makes about predicates.
Answers: 1. A method to read a base relation (full table scan, index scan); 2.
C = B(outer) + ceil(B(outer)/(M-2)) * B(inner)where M = number of buffer pages available; 3. That predicates are independent (or uniform distribution of values).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?