Query optimization (code by Claude, guidance by Georgios Evangelidis)
An optimizer turns a declarative SQL query into an efficient evaluation plan. It parses the query into relational algebra, rewrites it with equivalences (pushing selections and projections down), estimates the size of every intermediate result from catalog statistics, and searches the space of plans, here with System R dynamic programming over left-deep join trees, choosing access paths and join methods by estimated I/O cost.
Catalog
| Relation | Pages | Tuples / page | Tuples |
|---|
Column statistics
| Column | Type | Bytes | NKeys | Low | High | Data |
|---|
Query
SELECT … FROM … WHERE (conditions, [NOT] IN / [NOT] EXISTS subqueries, joined by AND) … GROUP BY … HAVING … ORDER BY; two blocks may be combined with UNION [ALL], INTERSECT or EXCEPT. Ctrl + Enter runs it.
Indexes
| On | Index | Type | Clustered | Pages |
|---|
Add
on
The cost model, and what it leaves out
- Cost is page I/O; CPU is ignored, and writing the final result is not counted, since every plan writes the same result.
- Reduction factors: column = value is 1/NKeys; a range on a numeric column is the fraction of [Low, High] it covers; column ≠ value is 1 − 1/NKeys; a range on a string column is 1/3 (the System R default); a join column = column is 1/max(NKeys). Predicates are assumed independent and values uniformly distributed.
- Index access: finding the first entry costs 1.2 I/Os with a hash index and 3 with a B+ tree; then each matching tuple costs 1 I/O through an unclustered index, while a clustered index reads ⌈matches / tuples per page⌉ pages.
- Composite indexes: a B+ tree on ⟨a, b, …⟩ can evaluate equalities on a prefix of its key followed by at most one range, and returns entries sorted on the next key column; a hash index needs an equality on every key column. Index nested loops can use a B+ tree whose first column is the join column, or a hash index on exactly that column.
- Histograms: with skewed data the uniform formulas can be far off. An equiwidth histogram splits the value range into buckets of equal width, an equidepth histogram into buckets holding about the same number of tuples; within a bucket, values are still assumed uniform. With skewed data, the Best plan tab re-costs the chosen plan on the real data and shows which plan perfect statistics would have chosen. Histograms are kept here for the skewed columns (Sailors.rating, Sailors.age, Reserves.bid).
- Nested queries: IN and EXISTS become semi-joins and NOT IN and NOT EXISTS anti-joins over the subquery's single table; a semi-join keeps an outer tuple with probability 1 − e^(−m), where m is its expected number of matches (matches assumed Poisson), and an anti-join with probability e^(−m). The subquery as written is also costed by nested iteration: once per outer tuple when correlated, or evaluated once and searched when not. NOT IN is treated like NOT EXISTS (NULLs are ignored).
- Set operations: each block is optimized on its own. UNION ALL concatenates; UNION, INTERSECT and EXCEPT remove duplicates by sorting both results or by hashing (free when the hash table fits in B − 2 pages, otherwise 2 × the pages of both results). Result sizes are upper bounds.
- Index-only evaluation: when an index contains every column a query needs from a relation, the data entries answer it and no record is read, so clustering no longer matters. A data entry is the key plus an 8-byte record id; B+ tree leaves are about 67% full and hash buckets about 80% full. Reaching a B+ tree leaf costs 2 I/Os for the inner levels, then one per leaf page read.
- Plans are left-deep: the outer input of each join is pipelined from the join below (it is never written to disk), and the inner input is a base relation. Cross products are considered only when the query has no join between some relations.
- The inner relation's own selections are applied either on the fly every time it is read or once, writing a smaller temporary relation; the cheaper option is used.
- Sorting uses external merge sort with B buffers. A sort-merge join sorts its inputs fully and then merges them; for grouping and ORDER BY the final merge pass feeds the next operator directly, so a sort costs 2P per pass except that the last pass only reads. A sort that fits in B pages costs no I/O.
- Interesting orders: a B+ tree index scan, a file scan of a relation with a clustered B+ tree, and a sort-merge join produce sorted output, and index nested loops keep the order of their outer input. For each set of relations, plans sorted on a join column, a single grouping column or a single ascending ORDER BY column are kept alongside the cheapest plan. Descending order and sorting on several columns are always done by an explicit sort here.
- Grouping: the number of groups is the product of NKeys of the grouping columns, capped by the input size. Hash-based grouping is free when the groups fit in B − 1 pages and otherwise partitions the input (2P); sort-based grouping costs one sort; sorted input costs nothing. HAVING uses the System R default reduction factor 1/3 per condition. DISTINCT is evaluated like grouping on the selected columns.
- With projections pushed down, each relation keeps only its output columns and join attributes above the scan, so intermediate tuples are narrower and fit more per page. Base relations are still read at full width. Switch it off to size intermediate results with full tuples, as most textbook examples do.