Lesson 2 of 12

How the Cost-Based Optimizer Chooses a Plan

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source

The one thing to understand first

For any non-trivial query there are many ways to get the answer — different scan methods, join orders, and join algorithms. The planner/optimizer (src/backend/optimizer/) enumerates candidate paths, estimates the cost of each, and picks the cheapest. It does not try every possibility exhaustively; it prunes aggressively.

The optimizer is a pure function: selectivity in, cost out. It almost always picks the right plan given accurate row counts, so plan debugging is not about outsmarting the planner — it is about finding the one row estimate that is wrong.

Paths and the cheapest-path principle

For each relation the planner builds Path objects — one per viable access method (seq scan, each usable index, bitmap). Paths carry a cost and useful properties such as <a class="sev1-termlink" href="https://thesev1database.com/glossary/pathkeys/" title="Pathkeys">sort order. At each level the planner keeps only the cheapest path for each distinct useful property (e.g. cheapest unordered, cheapest sorted by X). This pruning is what keeps planning tractable.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • Where the cost numbers come from
  • The join search
  • Choosing a join algorithm
  • Why estimates matter more than the algorithm
  • Layer 3 — Watch it happen on your own database
  • Layer 4 — The levers this hands you
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Was this helpful?

← Back to 02 — Performance: Query & Index Mastery