Query Optimizer & Statistics

Concept. The optimizer estimates the cost of alternative plans and chooses the cheapest.

The Journey: SQL to a Plan

Five-stage pipeline: SQL (declarative) to parse and bind, to a logical plan of equivalence-preserving relational-algebra rewrites that defines the result, to the physical-plan cost search (pick join order, algorithm, access path; dynamic programming reuses the best sub-plan per table subset so n! becomes about 2 to the n; cost each from statistics) where speed is decided, to executing the chosen operator tree about 100x faster than naive.

Figure 1. Preserve the query’s result; choose how to compute it using estimated costs.

Algorithm Lego Blocks

The optimizer picks from a catalog of algorithm "blocks" and assembles them into a physical plan. Four families:

Algorithm 'lego blocks' the optimizer can mix and match into physical plans. Four columns: Access Methods (sequential, index, bitmap scans), Partition/Sort (Hash Partition, BigSort), Aggregation (Hash Aggregate, Sort Aggregate), Join Algorithms (Hash Join, Sort-Merge Join, Block Nested Loop).

Figure 2. For the recommendation query, choose access methods, a join, an aggregation method, and a final sort by count. Partition or sort only where an operator needs it. Compare the complete plans using estimated rows, pages, memory, and existing order.

Statistics: estimating the work

  1. Sample: inspect a sample of the table (example: 1% of its rows).

  2. Summarize: keep row and page counts, distinct-value counts, common-value frequencies, and histograms of value ranges.

  3. Store and use: save these compact summaries in the database’s system catalog, organized by table and column. The optimizer uses them to estimate output rows and compare plan costs.

Example: for WHERE user_id BETWEEN 1 AND 100, suppose the statistics estimate that 1% of rows match. That is the selectivity. With 1 million input rows, the estimated output cardinality is 1,000,000 × 1% = 10,000 rows.

For our recommendation query, distinct counts and common-value frequencies help estimate join matches and the number of song groups. These row estimates determine the page counts used in the cost formulas.

When statistics go stale

As data changes, old summaries can lead to poor plan choices. Run ANALYZE to refresh them; PostgreSQL can also do this automatically. Statistics are estimates, so even fresh statistics can be wrong.

Compare plans: add up their I/O costs and choose the smaller total.