A cost-based optimizer (CBO) is the component of a relational database engine that chooses an execution plan by estimating the cost of many alternative plans and selecting the one with the lowest predicted resource consumption. In database Performance work, it is the mechanism that turns a declarative SQL statement into concrete operations such as index scans, hash joins and sorts, which makes it central to how fast queries run in modern Databases.
Before cost-based optimization became standard, many engines used a rule-based optimizer, which applied a fixed ranking of access paths regardless of data volume. The CBO replaced that approach because the best plan depends on the data: a filter that returns ten rows calls for an index lookup, while the same filter returning half the table is usually faster with a full scan.
How a cost-based optimizer selects a plan
A cost-based optimizer works in three broad stages: it rewrites the query into an equivalent but simpler form, it enumerates candidate plans, and it assigns each candidate a numeric cost. The plan with the lowest cost becomes the execution plan that the executor runs.
The cost is an abstract unit, not a measured time. It combines estimated I/O, CPU work and memory use, weighted by configurable constants. PostgreSQL, for example, expresses costs relative to reading one sequential page, while Oracle Database and SQL Server use their own internal cost models. Because the units differ, costs are comparable only within one engine and one query.
The following table summarizes the main stages and what each one contributes to the final plan.
| Stage | What happens | Main output |
|---|---|---|
| Parsing and binding | SQL text is checked and names are resolved | Validated query tree |
| Query rewrite | Subqueries are flattened, views merged, predicates pushed down | Simplified logical plan |
| Plan enumeration | Join orders, join methods and access paths are generated | Set of candidate plans |
| Cardinality estimation | Row counts are predicted for each operator | Estimated rows per step |
| Costing and selection | Cost formulas are applied and the cheapest plan is kept | Final execution plan |
Enumeration is the hardest part to scale. The number of possible join orders grows factorially with the number of tables, so engines use dynamic programming for small joins and switch to heuristics or genetic search for large ones. PostgreSQL, for instance, falls back to its genetic query optimizer once a query exceeds a configurable threshold of joined relations, by default twelve.
Inputs that drive cost estimates
The quality of a cost-based optimizer depends almost entirely on the accuracy of its inputs. The most important input is cardinality, the predicted number of rows each operator produces, because every later cost calculation multiplies that estimate.
The table below lists the inputs that most engines rely on and how each influences plan choice.
| Input | Typical source | Effect on the plan |
|---|---|---|
| Table row count | Optimizer statistics | Sets the scale of every scan estimate |
| Column histograms | Sampled value distributions | Predicts selectivity of range and equality filters |
| Distinct value counts | Statistics gathering job | Drives join size and grouping estimates |
| Index clustering | Correlation between index and table order | Decides between index scan and full scan |
| Cost constants | Server configuration | Weights random I/O against sequential I/O and CPU |
| Available memory | Work memory settings | Determines whether hashes and sorts spill to disk |
When predicates involve several columns, most optimizers assume statistical independence and multiply individual selectivities. This assumption fails for correlated columns such as city and postal code, and it is the most common cause of large misestimates. Extended or multi-column statistics, available in PostgreSQL, Oracle and SQL Server, reduce this error for known correlations.
Cost-based optimizer compared with other approaches
A cost-based optimizer differs from older and newer approaches mainly in how it decides between alternatives. The comparison below places it alongside the rule-based model and adaptive techniques that extend it.
| Approach | Decision basis | Strength | Weakness |
|---|---|---|---|
| Rule-based optimizer | Fixed ranking of access paths | Predictable and stable plans | Ignores data volume and distribution |
| Cost-based optimizer | Estimated cost from statistics | Adapts plans to actual data | Sensitive to stale or wrong statistics |
| Adaptive execution | Runtime row counts adjust the plan | Corrects misestimates mid-query | Adds overhead and complexity |
| Learned optimizers | Models trained on past executions | Can capture correlations | Still mostly experimental in production |
Related tools interact closely with the optimizer. A query hint overrides part of its decision, plan baselines or plan guides freeze a known good plan, and a query cache bypasses optimization entirely for repeated identical statements. Each of these trades the adaptability of cost-based selection for predictability.
Working effectively with the optimizer
Practitioners get the best results by keeping statistics current and reading execution plans rather than forcing behavior with hints. The usual workflow is to compare estimated and actual row counts, find the operator where they diverge, and fix the input that caused the gap.
The following decision table maps common situations to a recommended response.
| Situation | Recommended action | Reason |
|---|---|---|
| Plan changed after bulk load | Refresh optimizer statistics | Row counts and histograms are outdated |
| Estimates off on correlated filters | Create multi-column statistics | Removes the independence assumption |
| Plan flips between parameter values | Review parameter sniffing and plan caching | One cached plan fits skewed values poorly |
| Optimization time is excessive | Simplify joins or limit search depth | Enumeration cost exceeds execution cost |
| Known good plan regresses | Pin it with a baseline, then investigate | Restores service while the cause is found |
Commands such as EXPLAIN ANALYZE in PostgreSQL or actual execution plans in SQL Server show both estimates and real figures. A misestimate of ten times or more at a join is usually enough to explain a poor join method or join order.
Limitations and common misconceptions
A cost-based optimizer is a model of reality, not a measurement of it, so its choices can be wrong even when it works exactly as designed. Experienced engineers keep the following limits in mind.
- Errors compound through joins: a small misestimate at the first join can grow by orders of magnitude after several joins.
- The lowest cost is not always the fastest plan, because cost constants rarely match the real storage, cache and concurrency conditions.
- Cached plans can become stale when data distribution shifts, even if statistics are later refreshed.
- Adding an index does not guarantee its use; the optimizer may correctly judge a full scan to be cheaper for low selectivity.
- Hints fix a symptom at one moment and can block better plans after the data or engine version changes.
In simple terms
A cost-based optimizer is like a navigation app for a database. You tell it where you want to go, meaning which data you need, and it considers many possible routes before picking the one it expects to be quickest.
To make that guess, it uses facts about the data, such as how many rows a table holds and how values are spread out. When those facts are accurate, it chooses well. When they are outdated, it can pick a slow route, just as a map without recent road closures would.
A practical example
An online retailer runs a nightly report joining an orders table of about 80 million rows with customers and products. After a large import of historical orders, the report suddenly takes 45 minutes instead of 3. The database administrator runs EXPLAIN ANALYZE and sees that the optimizer expected 2,000 rows from a date filter but actually received 1.4 million, so it chose a nested loop join that performed millions of index lookups.
The administrator refreshes the optimizer statistics on the orders table and adds a multi-column statistic on order date and status, which are strongly correlated. The optimizer now estimates the row count within a few percent and selects a hash join. The report returns to about 3 minutes without any hint or code change, and the team schedules statistics gathering after every bulk load.