IIT Madras Zanzibar · Teaching

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

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:

n tables → n! orderings (ignoring Cartesian products) n=2: 2 plans n=3: 6 plans n=5: 120 plans n=10: 3,628,800 plans n=15: > 1 trillion plans

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

Left-deep tree (preferred): Bushy tree: ⋈ ⋈ / \ / \ ⋈ D ⋈ ⋈ / \ / \ / \ ⋈ C A B C D / \ A B Left-deep: one input is always a base table → pipelining works Bushy: requires materializing intermediate results; rarely used

2.2 Dynamic Programming Algorithm

  1. Enumerate all single-table access paths (heap scan, index scans)
  2. For each pair of tables, compute the optimal join of those two tables using the best access paths
  3. For each triple of tables, compute optimal join using already-computed pairwise costs
  4. 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

EXPLAIN ANALYZE SELECT e.name, d.dept_name FROM employees e JOIN departments d ON e.dept_id = d.dept_id WHERE e.salary > 80000; Output: Hash Join (cost=120.45..580.32 rows=1200 width=48) (actual time=2.1..18.3 ms) Hash Cond: (e.dept_id = d.dept_id) -> Seq Scan on employees (cost=0..310.00 rows=1400 width=36) Filter: (salary > 80000) Rows Removed by Filter: 8600 -> Hash (cost=80.00..80.00 rows=3236 width=20) -> Seq Scan on departments (cost=0..80.00 rows=3236 width=20) Planning Time: 0.8 ms Execution Time: 18.9 ms

3.2 Key Fields to Read

FieldMeaning
cost=X..YEstimated startup cost X and total cost Y in abstract units (page reads)
rows=NEstimated output cardinality (rows)
actual time=A..B msReal elapsed time (requires ANALYZE keyword)
Rows Removed by FilterHow many rows did the predicate filter out: high = good selectivity
Seq ScanFull table scan; check if an index scan would be cheaper
Index ScanB+ tree or hash index used; cheaper for selective predicates
Hash Join / Merge Join / Nested LoopJoin algorithm chosen; check if appropriate for the table sizes

3.3 SQL Server EXPLAIN (Execution Plan)

-- SQL Server: graphical plan in SSMS, or text plan: SET STATISTICS IO ON; SET STATISTICS TIME ON; SELECT ...; -- Or: EXPLAIN via: SET SHOWPLAN_ALL ON; SELECT ...;

4. Practical Query Tuning

4.1 Create Indexes on Predicates and Join Keys

-- Slow: salary > 80000 on 1M row table, no index SELECT * FROM employees WHERE salary > 80000; -- Seq Scan: 10,000 I/Os -- Fix: create a B+ tree index CREATE INDEX idx_salary ON employees(salary); -- Now: Index Range Scan: ~200 I/Os for 2% selectivity

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) = 2020WHERE hire_date BETWEEN '2020-01-01' AND '2020-12-31'
WHERE salary * 1.1 > 88000WHERE 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

CREATE INDEX idx_dept_salary ON employees(dept_id, salary); -- Index used: WHERE dept_id = 5 AND salary > 80000 ✓ (leftmost column matched) -- Index used: WHERE dept_id = 5 ✓ (prefix of index) -- Index NOT used: WHERE salary > 80000 ✗ (dept_id not in predicate)

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.

CREATE INDEX idx_covering ON employees(dept_id, salary, name); SELECT name, salary FROM employees WHERE dept_id = 5; -- All three columns (dept_id for filter, salary and name for output) are in index -- → Index-Only Scan; no heap page reads needed

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:

-- PostgreSQL: refresh statistics ANALYZE employees; -- SQL Server: update statistics UPDATE STATISTICS employees; -- SQL Server: auto-statistics update (on by default, but may lag on large tables) ALTER DATABASE MyDB SET AUTO_UPDATE_STATISTICS ON;

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