Lecture: Lecture 15 - Query Optimization
Related: DBMS Architecture and Query Processing, Physical Access Structures and Access Methods

Why optimization exists

SQL describes the desired result, not the physical procedure. The same result may come from a full scan, an index lookup, different join orders or different join algorithms. The optimizer searches for a cheaper strategy while preserving the result.

Pipeline

  1. Lexical analysis checks words and keywords.
  2. Syntactic analysis checks SQL grammar.
  3. Semantic analysis checks that referenced tables and attributes exist.
  4. The statement becomes a relational-algebra expression or query tree.
  5. Algebraic optimization applies safe equivalence transformations.
  6. Cost-based optimization compares physical plans using statistics.
  7. The DBMS produces executable access code and records dependencies such as required indexes.

Compile-and-go executes immediately without storing the plan. Compile-and-store keeps the plan and dependencies for later execution, but it may need recompilation after relevant structures change.

High-value transformations

Selections (σ) choose rows; projections (π) choose columns; joins (⋈) combine matching rows.

  • Split σ(A AND B)(T) into two selections.
  • Push a selection below a join when its predicate uses only one input.
  • Push projections down while preserving output columns, join columns and predicate columns.
  • Replace σ(join condition)(R × S) with R ⋈ S.
  • Reorder joins when commutativity and associativity preserve the result.

The purpose is to reduce intermediate rows and columns before expensive operations.

Worked trace

For EMP ⋈ DEPT with Salary > 1000, an efficient tree is:

Project DName
  Join
    Project Dept#
      Select Salary > 1000
        EMP
    Project Dept#, DName
      DEPT

The DBMS filters EMP before joining and carries only the attributes needed later.

Common confusion

Algebraic optimization changes the expression into an equivalent expression. Cost-based optimization chooses among physical ways to implement that expression. The first is mainly about correctness-preserving rewrites; the second depends on data distribution, indexes and estimated costs.

Retrieval questions

Why push a filter before a join? It reduces the number of rows entering the join.

Why cannot every column be projected away before a join? The join predicate and any later operation still need their columns.

Why is a Cartesian product followed by an equality filter usually rewritten as a join? A Cartesian product creates every pair, while a join creates only matching pairs.