skip to content
10, 10 chapters
the optimizer
everything.optimizer

the optimizer

how postgres guesses row counts, prices every plan and picks the cheapest. and how it gets that wrong.

start part 10part 10 of 18, 10 chapters
  1. 10.01the cost modelseq_page_cost, random_page_cost, cpu_tuple_cost. price a plan by hand and get the planner's number.
  2. 10.02pg_stats and ANALYZEnull fraction, distinct counts, most common values, histograms, and the 30,000-row sample behind them.
  3. 10.03estimating rowshow a WHERE becomes a row count: MCVs, histogram buckets, and the default guesses when there's nothing to go on.
  4. 10.04when estimates go wrongthe independence assumption, functions in WHERE, and the 1,000x miss that picks a nested loop.
  5. 10.05extended statisticsCREATE STATISTICS for columns that move together. city and country, and a 35x misestimate fixed.
  6. 10.06join order searchn tables, n! orders. dynamic programming, join_collapse_limit, and the genetic optimizer past 12 tables.
  7. 10.07how subqueries get plannedpull-up, semi joins, hashed SubPlans, and why IN and EXISTS often end up as the same plan.
  8. 10.08prepared statements and generic plansfive custom plans, then maybe one generic plan forever. plan_cache_mode, explained.
  9. 10.09finding slow queriespg_stat_statements, auto_explain, and the N+1 pattern seen from the database's side.
  10. 10.10steering the plannerpostgres has no hints. enable_* switches, cost settings, query rewrites, and what you can actually control.