Lecture: Lecture 15 - Query Optimization
Related: Query Cost Estimation and Access Selection, Physical Access Structures and Access Methods
Nested-loop join
The DBMS scans the outer table. For each outer row, it scans or searches the inner table for matches. It is good when the inner table is small, fits in memory or has an index on the join attribute. It is asymmetric, so choosing the inner table matters.
Merge join
Both inputs are sorted on the join key and scanned together. Matching values are emitted as the scans advance. It works well for large sorted inputs, especially when sorting has already happened or a clustered index provides the order. Sorting unsorted inputs is its main cost.
Hash join
The DBMS applies the same hash function to both join inputs. Equal join values land in corresponding buckets, where matching rows are compared. Hash join is often very fast for equality joins, but it is not naturally suited to inequality predicates and needs suitable memory.
Bitmap join index
A bitmap join index precomputes which rows of one table join with rows of another. It is especially useful in OLAP queries with a large fact table and several dimensions. Bitmap predicates can be combined before the fact table is read.
Plan selection
With three tables, multiple join orders and several algorithms, the optimizer may compare dozens of plans. A search tree represents choices such as:
- How each table is read
- Which join order is used
- Which algorithm implements each join
- When sorting occurs
Leaves are complete plans. The optimizer selects the leaf with the lowest estimated cost, often using pruning techniques such as branch and bound. The result is an approximation of the best plan because exhaustive search can itself be expensive.
Grouping
Sort-based grouping orders rows by the group attributes before calculating aggregates. Hash-based grouping puts rows into buckets by group key and processes each bucket. Materialized views can provide already-computed summaries.
Retrieval questions
Why does join order matter if joins are mathematically associative? Different orders create different intermediate result sizes and therefore different I/O and CPU costs.
When is nested-loop join attractive? When the inner input is small or indexed.
Which method is naturally suited to an equality join without sorting both inputs? Hash join.