arthrop0d

Brief articles on varied topics.

SQL Cardinality Estimation and Query Plan Choice

sqldatabases

Cardinality estimation is the optimizer’s attempt to predict how many rows each step of a SQL query will produce. It uses stored table statistics—especially row counts, distinct-value counts, and histograms—to compare possible execution plans before choosing one.

The problem: choosing a plan without running the query

A query can often be executed in many logically equivalent ways. For example, a database might:

The best choice depends heavily on intermediate result sizes. Joining two inputs of 100 rows is a different problem from joining two inputs of 100 million rows. But trying every plan by executing it would defeat the purpose of optimization.

The optimizer therefore builds candidate plans and estimates their cardinality, meaning the number of rows produced by each operation. It combines those estimates with resource costs such as disk reads, memory use, and CPU work. The plan with the lowest estimated cost usually wins.

Without useful estimates, the optimizer must rely on fixed guesses. Those guesses can produce a plan that looks reasonable in general but is disastrous for the particular data distribution in a database.

The statistics behind an estimate

A database collects statistics about tables and columns, either automatically or through an explicit statistics command. The exact statistics vary by database system, but common values include:

These are summaries, not a second copy of the table. They deliberately use much less space and are therefore only an approximation. Statistics can also become stale as rows are inserted, updated, or deleted.

The optimizer converts a predicate’s expected fraction of matching rows into selectivity. If a table has 1,000,000 rows and a predicate is estimated to have 1% selectivity, the estimated result is 10,000 rows:

SELECT *
FROM orders
WHERE customer_id = 42;

For an equality predicate, a simple estimate assumes values are evenly distributed. If customer_id has an NDV of 100,000, the estimate for one value is approximately:

selectivity ≈ 1 / 100,000
estimated rows ≈ table rows / 100,000

This works tolerably when values are uniform. It is poor when one customer accounts for a large fraction of all orders. Most-common-value statistics let an optimizer treat that customer differently from an ordinary value.

What histograms add

An NDV says how many values exist, but not where they occur. A histogram divides a column’s value range into buckets and records information about the rows in each bucket. It can reveal, for example, that most dates are recent or that a numeric column has a large gap between two clusters of values.

For a range predicate such as:

SELECT *
FROM events
WHERE created_at >= DATE '2025-01-01';

the optimizer locates the boundary in the histogram and estimates what fraction of rows lies above it. It can do the same for <, <=, and BETWEEN predicates.

Histogram designs differ. Some make buckets contain similar numbers of rows; others divide the value range more evenly. Either way, the buckets let the optimizer avoid the simplistic assumption that every part of the range is equally populated. A histogram is still coarse: a sharp spike inside one bucket may remain invisible.

For predicates combined with AND, optimizers often estimate each predicate’s selectivity and multiply them. This assumes the predicates are independent. For example, it may estimate that country = 'US' and language = 'en' are unrelated. Real data often violates that assumption. Correlated columns, such as country and currency, can make the combined estimate much too small or too large. Some systems collect multi-column or extended statistics to capture important dependencies.

Estimating joins

For an equality join, the optimizer needs to predict how many rows will match between the two inputs. Consider:

SELECT *
FROM orders o
JOIN customers c ON c.id = o.customer_id;

If customers.id is unique and every order has a matching customer, the join may produce roughly as many rows as orders. Uniqueness information is valuable because it tells the optimizer that each order can match at most one customer.

For less constrained joins, the optimizer uses input row counts and NDVs. A simplified intuition is that matching rows are likely when values overlap, and that a column with many distinct values produces fewer matches per value than a column with few distinct values. Histograms and most-common-value data improve the estimate when the join keys are skewed.

Joins are also where estimation errors compound. If the optimizer estimates 100 rows from one operation but the actual result is 100,000, every later operation that consumes that result may be costed using the wrong input size. A modest error at each filter can become a huge error across a long join chain.

How estimates choose the plan

The optimizer uses estimated cardinalities to compare access paths, which are the ways it can retrieve rows. An index scan may be cheaper when a predicate returns a few rows. A sequential scan may be cheaper when it returns a large fraction of the table, because reading the table in bulk avoids many scattered page reads.

The estimates also influence join algorithms:

For multiple tables, the optimizer considers join orders. It generally prefers to reduce the size of intermediate results early, because later joins then process fewer rows. But that rule is balanced against access costs, available indexes, and join algorithms. A slightly larger intermediate result may still be cheaper if it avoids an expensive sort or scan.

You have likely seen these estimates in EXPLAIN output: an operation may show an estimated row count alongside an actual row count when execution statistics are enabled. A large difference between the two is a clue that the optimizer’s model is wrong—perhaps because statistics are stale, a histogram misses skew, or columns are correlated. Updating statistics can help, but it cannot make a single-column summary fully describe every relationship in the data.

Cardinality estimation is therefore not the query’s result calculation. It is the optimizer’s predictive model: an approximate forecast of row counts used to choose how the database will obtain and combine those rows.

← All articles