Cost-based optimizer

Also known as: CBO

On this page 7

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.

StageWhat happensMain output
Parsing and bindingSQL text is checked and names are resolvedValidated query tree
Query rewriteSubqueries are flattened, views merged, predicates pushed downSimplified logical plan
Plan enumerationJoin orders, join methods and access paths are generatedSet of candidate plans
Cardinality estimationRow counts are predicted for each operatorEstimated rows per step
Costing and selectionCost formulas are applied and the cheapest plan is keptFinal execution plan
Stages of cost-based plan selection

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.

InputTypical sourceEffect on the plan
Table row countOptimizer statisticsSets the scale of every scan estimate
Column histogramsSampled value distributionsPredicts selectivity of range and equality filters
Distinct value countsStatistics gathering jobDrives join size and grouping estimates
Index clusteringCorrelation between index and table orderDecides between index scan and full scan
Cost constantsServer configurationWeights random I/O against sequential I/O and CPU
Available memoryWork memory settingsDetermines whether hashes and sorts spill to disk
Key inputs to the cost model

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.

ApproachDecision basisStrengthWeakness
Rule-based optimizerFixed ranking of access pathsPredictable and stable plansIgnores data volume and distribution
Cost-based optimizerEstimated cost from statisticsAdapts plans to actual dataSensitive to stale or wrong statistics
Adaptive executionRuntime row counts adjust the planCorrects misestimates mid-queryAdds overhead and complexity
Learned optimizersModels trained on past executionsCan capture correlationsStill mostly experimental in production
Approaches to plan selection

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.

SituationRecommended actionReason
Plan changed after bulk loadRefresh optimizer statisticsRow counts and histograms are outdated
Estimates off on correlated filtersCreate multi-column statisticsRemoves the independence assumption
Plan flips between parameter valuesReview parameter sniffing and plan cachingOne cached plan fits skewed values poorly
Optimization time is excessiveSimplify joins or limit search depthEnumeration cost exceeds execution cost
Known good plan regressesPin it with a baseline, then investigateRestores service while the cause is found
Responding to optimizer problems

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.