Optimizer statistics

Also known as: table statistics

On this page 8

Optimizer statistics are stored summaries of the data in tables and indexes, such as row counts, distinct values, null fractions and value distributions, that a cost-based optimizer uses to estimate how many rows each step of a query will return. In databases, query performance depends less on raw hardware than on whether the optimizer chooses a sensible execution plan, and that choice is only as good as the statistics behind it.

Also called table statistics, they do not store the data itself. They are a compact, approximate model of the data, refreshed periodically, and the gap between that model and reality is one of the most common root causes of sudden slowdowns in production systems.

How optimizer statistics drive plan selection

Optimizer statistics feed the cardinality estimation step that precedes every cost calculation. For each predicate, join and grouping, the optimizer estimates the number of qualifying rows, converts those estimates into I/O and CPU cost units, and compares alternative plans. A plan that reads 50 rows through an index and a plan that scans 50 million rows look identical to the parser; only the statistics tell them apart.

The estimates multiply as they travel through a plan. If a filter is estimated at 1 percent selectivity but actually matches 30 percent, every join above it inherits the error, which is why a single stale statistic can turn a nested loop join into a disaster that runs for hours. Experienced practitioners treat estimation errors of more than one order of magnitude as a strong signal that statistics need attention.

The table below lists the main kinds of statistics that engines collect and the decisions each one influences.

StatisticWhat it describesDecision it informs
Row countNumber of rows in the tableScan cost, join order
Page or block countPhysical size on diskSequential scan cost
Number of distinct valuesCardinality of a columnEquality selectivity, grouping size
Null fractionShare of rows that are nullSelectivity of IS NULL filters
HistogramDistribution of values in bucketsRange predicate selectivity
Most common valuesFrequent values and their frequenciesSelectivity for skewed data
CorrelationPhysical order versus logical orderIndex scan versus heap fetch cost
Core statistics and what they influence

Histograms, distinct values and data skew

A histogram divides the range of a column into buckets so that the optimizer can estimate how many rows fall between two values. Equi-depth histograms, in which each bucket holds roughly the same number of rows, are the most common design because they describe dense regions precisely. Oracle additionally offers frequency, top-frequency and hybrid histograms, while SQL Server stores up to 200 steps per statistics object.

Data skew is the main reason histograms matter. When one customer owns 40 percent of all orders, an estimate based only on the number of distinct values would assume an even spread and badly underestimate that customer. A most common values list captures such outliers explicitly, so the optimizer can choose a full scan for the heavy value and an index lookup for the rare ones.

Multi-column relationships are a separate problem. By default, optimizers assume that predicates are statistically independent, so a filter on city and postal code is estimated as the product of two selectivities, although one practically implies the other. Extended statistics (PostgreSQL), column groups (Oracle) and multi-column statistics (SQL Server) correct this by recording combined distinct counts or dependencies.

How major engines collect and refresh statistics

Every major engine gathers statistics by sampling rather than reading every row, because a full scan of a multi-terabyte table would be too expensive to repeat. The comparison below summarizes the default behavior of widely used systems.

EngineManual commandAutomatic refreshSampling approach
PostgreSQLANALYZEAutovacuum daemon after about 10 percent of rows changeFixed sample of 300 times the statistics target
Oracle DatabaseDBMS_STATS.GATHER_TABLE_STATSNightly maintenance window for stale objectsAdaptive sampling with approximate distinct counts
SQL ServerUPDATE STATISTICSAuto update when a modification threshold is crossedSample size scaled to table size
MySQL InnoDBANALYZE TABLEPersistent statistics recalculated after about 10 percent changeRandom index pages, set by a page count
Statistics collection in common database engines

Sampling introduces a trade-off between accuracy and maintenance cost. Larger samples improve distinct value estimates, which are notoriously hard to derive from small samples, but they lengthen the collection job and increase I/O. Raising the statistics target or sample size for a few problematic columns is usually better than raising it for the whole database.

Modification thresholds create a well-known blind spot. On a table with 100 million rows, a 10 percent threshold means 10 million rows can change before a refresh occurs, and new values at the end of an ascending key, such as today’s timestamps, may be missing from the histogram entirely. This ascending key problem causes estimates of one row for data that actually contains thousands.

Optimizer statistics are easy to confuse with other performance data because several features share similar names. The table below separates them by purpose.

ConceptMain consumerContentPurpose
Optimizer statisticsCost-based optimizerData distribution summariesEstimate rows and choose plans
Workload statisticsAdministrators and toolsExecuted queries and timingsFind expensive queries
Execution planEngine and administratorsChosen operators and estimatesDescribe how a query runs
Query hintOptimizerExplicit plan instructionsOverride estimated choices
System statisticsCost modelCPU speed and I/O throughputCalibrate cost units
Statistics versus neighboring performance data

Workload views such as pg_stat_statements or a slow query log reveal which queries suffer, while optimizer statistics often explain why the plan was wrong. Query hints and plan guides can mask a bad estimate, but they freeze a decision that may become wrong as data grows, so fixing the statistics is generally the preferred first step.

Managing statistics in practice

Sound statistics management combines automatic maintenance as a baseline with targeted manual action. Automatic jobs handle gradual change well, but they cannot anticipate events that alter data in bulk.

SituationRecommended actionReason
After a bulk insert or loadAnalyze the loaded table immediatelyAutomatic thresholds lag behind large loads
After creating an indexGather index and column statisticsNew access paths need accurate costs
Temporary or staging tablesAnalyze before the dependent queries runAutovacuum may never visit short-lived tables
Heavily skewed columnRaise histogram resolution for that columnDefault buckets hide frequent values
Correlated filter columnsCreate extended or multi-column statisticsIndependence assumption underestimates rows
Major version upgradeRegather all statisticsSome upgrades do not migrate statistics
Situations that call for a manual statistics refresh

Some teams deliberately lock statistics on volatile tables, preserving a representative snapshot so that plans remain stable regardless of the moment the collection job runs. This approach suits queue tables that fluctuate between empty and full, but it requires periodic review because a locked snapshot slowly drifts away from the real data.

Common failure modes and misconceptions

Most statistics problems present as plan regressions: a query that ran in milliseconds yesterday suddenly takes minutes, with no code change. The following points capture the mistakes and misconceptions that practitioners encounter most often.

  • Stale statistics after large data changes cause row estimates that are wrong by orders of magnitude.
  • Fresh statistics are not always better: a refresh can expose a plan change that performs worse, so critical systems often test plan stability.
  • Parameter-sensitive queries may use one plan for all values even when statistics describe heavy skew.
  • Functions on columns, such as lower(email), hide the column from its statistics unless an expression index or expression statistics exist.
  • Comparing estimated and actual rows in the execution plan is the fastest way to confirm a statistics problem.

Explained without jargon

Imagine planning a trip through a city using a map. If the map is current, you pick the fastest route. If it is ten years old, you may drive straight into a road that no longer exists. Optimizer statistics are the database’s map of its own data.

Before running a request, the database looks at this map to guess how much data it will have to handle, then picks the quickest method. When the map is accurate, requests are fast. When it is outdated, the database makes confident but wrong choices, and requests that used to be quick become painfully slow. Keeping the statistics current is therefore one of the cheapest ways to keep a database fast.

A typical use case

An online retailer runs a nightly job that loads about 4 million new order rows into a table that already holds 60 million. The next morning, the order history report, which normally finishes in 2 seconds, takes more than 6 minutes. The execution plan shows the optimizer estimated 1 row for the date filter on the newest orders, so it chose a nested loop join that probed the customer table millions of times.

The database team adds an explicit ANALYZE step at the end of the load job and raises the statistics target on the order date column. The optimizer now estimates about 4 million rows, switches to a hash join, and the report returns to under 3 seconds. The change costs roughly 40 seconds of extra processing per night and removes the recurring morning incidents.