Module 9: Query Processing & Transactions · Lecture 40 · Week 14
Query Optimization & Join Ordering
How the optimizer chooses join order, uses EXPLAIN PLAN, and how you can guide it with hints and indexes
Learning Objectives
- Explain why join order matters and how the number of possible orderings grows with the number of tables
- Describe the System R dynamic programming approach to finding optimal left-deep join trees
- Interpret an EXPLAIN / execution plan output from SQL Server or PostgreSQL
- Apply practical query tuning techniques: index creation, predicate rewriting, join hints
1. Why Join Order Matters
The most impactful decision the query optimizer makes is join order. Because join is commutative (R ⋈ S = S ⋈ R) and associative ((R ⋈ S) ⋈ T = R ⋈ (S ⋈ T)), there are many equivalent orderings. The number of left-deep join trees for n relations is:
The cost difference between the best and worst join order can be orders of magnitude. Getting join order right is one of the most decisive jobs of the optimizer.
2. The System R Optimizer (Dynamic Programming)
The IBM System R query optimizer (1979) remains the conceptual basis for most modern optimizers. It uses dynamic programming to avoid re-computing costs for overlapping subproblems.
2.1 Left-Deep vs. Bushy Join Trees
2.2 Dynamic Programming Algorithm
- Enumerate all single-table access paths (heap scan, index scans)
- For each pair of tables, compute the optimal join of those two tables using the best access paths
- For each triple of tables, compute optimal join using already-computed pairwise costs
- Continue until all n tables are joined: return the plan with minimum total cost
At each step, the optimizer uses cardinality estimates and cost formulas. The key insight is: an optimal plan for n tables must use optimal plans for subsets of those tables (optimal substructure → dynamic programming applies).
2.3 Interesting Orders
The optimizer may choose a slightly more expensive join at an early step if the output is sorted in an "interesting order" (e.g., sorted on a future join key or on an ORDER BY attribute). This avoids a sort step later, making the overall plan cheaper.
3. Reading EXPLAIN Plans
Both PostgreSQL and SQL Server expose the optimizer's chosen plan with EXPLAIN / EXPLAIN ANALYZE.
3.1 PostgreSQL EXPLAIN ANALYZE
3.2 Key Fields to Read
| Field | Meaning |
|---|---|
| cost=X..Y | Estimated startup cost X and total cost Y in abstract units (page reads) |
| rows=N | Estimated output cardinality (rows) |
| actual time=A..B ms | Real elapsed time (requires ANALYZE keyword) |
| Rows Removed by Filter | How many rows did the predicate filter out: high = good selectivity |
| Seq Scan | Full table scan; check if an index scan would be cheaper |
| Index Scan | B+ tree or hash index used; cheaper for selective predicates |
| Hash Join / Merge Join / Nested Loop | Join algorithm chosen; check if appropriate for the table sizes |
3.3 SQL Server EXPLAIN (Execution Plan)
4. Practical Query Tuning
4.1 Create Indexes on Predicates and Join Keys
4.2 Rewrite Predicates to Be Sargable
A predicate is SARGable (Search ARGument-able) if the optimizer can use an index for it. Non-sargable predicates force a full scan.
| Non-Sargable (slow) | Sargable Rewrite |
|---|---|
WHERE YEAR(hire_date) = 2020 | WHERE hire_date BETWEEN '2020-01-01' AND '2020-12-31' |
WHERE salary * 1.1 > 88000 | WHERE salary > 80000 |
WHERE UPPER(name) = 'ALICE' | WHERE name = 'Alice' (with case-insensitive collation) |
WHERE name LIKE '%alice%' | WHERE name LIKE 'alice%' (leading wildcard prevents index use) |
4.3 Avoid SELECT *
Selecting only needed columns reduces I/O (especially in columnar stores), enables index-only scans, and reduces network transfer.
4.4 Composite Index Column Order
Always place the most selective column, or the equality column, first in a composite index. Range columns go last.
4.5 Covering Indexes (Index-Only Scans)
Covering Index
An index covers a query if all columns referenced in the query (SELECT list + WHERE + JOIN ON) are present in the index. The executor can answer the query entirely from the index without accessing the heap file. Cost = O(log_d n + output pages in index): no heap I/Os.
5. Statistics and ANALYZE / UPDATE STATISTICS
The optimizer's cost estimates are only as good as its statistics. If table statistics are stale (after a large batch load, for example), the optimizer may make poor plan choices. Run:
Stale Statistics: A Common Performance Trap
After bulk loading 10 million rows into a table that previously had 10,000 rows, the optimizer may still believe the table is small and choose a nested-loop join instead of a hash join. Always run ANALYZE / UPDATE STATISTICS after significant data changes.
6. Summary
- Join order affects query cost by orders of magnitude; n tables have n! orderings
- The System R dynamic programming optimizer finds the optimal left-deep join tree in O(2^n) time using interesting orders
- EXPLAIN / EXPLAIN ANALYZE shows the physical plan; look for unexpected seq scans, bad cardinality estimates, and wrong join algorithms
- Key tuning: create indexes on filter/join columns, write sargable predicates, use composite and covering indexes
- Keep statistics current with ANALYZE; stale stats cause plan regressions