arthrop0d

Brief articles on varied topics.

SQL Cardinality Estimation and Query Plans

sqldatabasesperformance

A SQL query planner’s cardinality estimator predicts how many rows each step of a query will produce. It uses statistics collected about table columns—especially value frequencies and histograms—to choose an execution plan before running the query.

That prediction matters because a plan that is efficient for 20 rows can be disastrous for 20 million. When the estimate is wrong, the planner can choose the wrong join algorithm, access path, or index.

The problem: choosing a plan before seeing the result

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

The database does not normally run all of these alternatives and keep the fastest one. It estimates the cost of each plan, then runs the cheapest-looking plan. Cardinality is the number of rows produced by a relation or an intermediate query step, and it is one of the most important inputs to that cost calculation.

Without statistics, the planner would have to rely on generic guesses. It might treat every value as equally common, or assume that a filter removes a fixed fraction of rows. Such guesses are sometimes reasonable, but real data is rarely uniform: a few customers may generate most orders, many status values may be rare, and timestamps often cluster around recent activity.

What column statistics contain

Statistics are usually collected by scanning a sample of a table rather than storing every value. The exact fields vary by database, but a column’s statistics commonly include:

An MCV list handles skew directly. If status = 'active' appears in 80% of rows, the estimator can use that frequency instead of pretending active is as rare as every other status.

A histogram is more useful for values that are not individually worth listing. Suppose a date column has boundaries dividing its observed values into ten buckets. If a predicate asks for dates inside one bucket, the estimator can approximate the fraction of rows in that range. For a range crossing several buckets, it combines the bucket fractions and interpolates at the boundaries.

For equality predicates not covered by the MCV list, the estimator can use the distinct-value count. A simple approximation is:

estimated matching rows ≈ non-null rows ÷ number of distinct values

That approximation is only good when values are reasonably even. MCVs and histograms exist largely because they often are not.

From predicates to cardinality

Consider a table with one million orders:

SELECT *
FROM orders
WHERE status = 'cancelled'
  AND created_at >= DATE '2025-01-01';

The estimator first predicts the rows matching each condition. It may know the frequency of cancelled from the MCV list and use the date histogram to estimate the recent portion of created_at.

To combine the conditions, many planners use an independence assumption: knowing a row’s status tells them nothing about its creation date. Under that assumption, they multiply the two selectivities. Selectivity is the fraction of rows expected to pass a predicate.

This assumption is often the source of a major error. A business may have cancelled mostly old orders, or mostly recent ones. The actual columns are correlated, but separate single-column statistics do not capture that relationship. Some databases can collect extended or multicolumn statistics to describe dependencies between columns, but those statistics must be enabled or maintained where supported.

The same process is applied at every stage. A filter’s estimated output becomes the input estimate for a join, aggregation, sort, or later filter. An early error can therefore become a large error downstream.

Why estimates determine joins and indexes

Join algorithms have different cost shapes:

If the estimator predicts ten rows from a filter, a nested loop with an index lookup may look cheap. If the filter actually returns ten million rows, that plan may perform millions of random lookups and be far slower than a sequential scan plus hash join.

Estimates also influence whether to use an index at all. An index is attractive when a predicate is selective—when it returns a small fraction of the table. For a large fraction, reading the table sequentially can be cheaper than traversing the index and then fetching many scattered table rows. A histogram that underestimates a common range can therefore cause an index scan where a sequential scan would have won.

Reading an unexpected plan

Most databases expose both estimated and observed row counts in an execution-plan tool. In PostgreSQL, for example, EXPLAIN ANALYZE adds actual execution measurements:

EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE status = 'cancelled';

A plan node might show an estimate of 100 rows but an actual count of 500,000. That is not merely an informational discrepancy: it explains why later choices may be inappropriate. Look for the first node where estimated and actual rows diverge sharply; downstream nodes often inherit the damage.

Common causes include stale statistics after a large data change, samples too small to represent a skewed distribution, correlated columns, parameter values with very different frequencies, and predicates involving expressions or functions whose distribution is unknown to the planner.

Refreshing statistics can fix changes in the data distribution, while higher statistics targets or multicolumn statistics can help with skew and correlation. But the goal is not to make every estimate exact. It is to make the estimates accurate enough that the planner chooses the right broad strategy.

Cardinality estimation is therefore the bridge between stored data and a query plan. Histograms and frequency statistics give the planner a model of that data; the model drives cost comparisons; and an inaccurate model can turn a theoretically sensible plan into an unexpectedly slow one.

← All articles