What you will be able to do
- Describe what a statistics object actually contains - header, density vector, histogram - and what the histogram is used for.
- Name the two CE model generations and which compatibility level selects each, including how to override per query.
- List the constructs the estimator cannot model well, and the rewrite or hint each one calls for.
- Tell a stale-statistics regression apart from a model limitation, because the fixes differ.
The optimiser does not know your data. It knows a statistics object per column or index - a summary built by sampling the table - and from that summary it estimates how many rows each predicate will match. Every decision in every plan descends from those estimates. When the estimate is wrong, the plan is wrong, and the fix is almost never in the plan - it is in what the estimator was given.
The analogy for the whole lesson is navigating with a survey map. The histogram is the map’s contour
detail over the first column - precise where it surveyed, silent past its edge. A stale map is a
survey from before the town grew: the fix is to survey again, which is UPDATE STATISTICS. A
structurally blind map never drew certain features at all - table variables, function-wrapped
columns, column-to-column comparisons - and no amount of re-surveying puts them on it; the fix is a
route that uses features the map actually has.
The most common mistake is treating every bad estimate as stale statistics: running
UPDATE STATISTICS against a construct the estimator cannot model, watching the estimate stay
wrong, and concluding the statistics are broken. The refresh fixes only the survey that predates
the data; when the estimate is structurally blind, the rewrite is the fix - and telling the two
apart before acting is the discipline this lesson exists for.
What a statistics object holds
Each statistics object (_WA_Sys_* auto-created ones, or index statistics) stores three things:
- Header - last-updated time, rows sampled, modification counter. Tells you whether the statistics are stale.
- Density vector - a fraction per column prefix measuring how distinct the key is; used for
equality on the full key and for
GROUP BYestimates. - Histogram - up to 200 steps over the leftmost column’s range, with range and distinct counts per step. This is what range predicates and joins are estimated from.
The histogram is the single most important input to plan quality, and it covers only the leading column of the index or statistics key. A query whose filter is on a later column falls back to the density vector - a weaker signal.
From your predicate to a row estimate
Predicate
A filter the optimiser must cost
Equality on the leftmost column uses the histogram directly - the ideal case
Histogram hit?
Step-level range counts for in-range values
A value past the histogram range edge is a classic underestimate on growing tables
Fallback
Density vector, or fixed assumptions for unknowns
Variables, functions, table variables, column-to-column comparisons - the CE guesses
Cardinality
An estimated row count per operator
Wrong rows in means wrong join type, wrong memory grant, wrong parallelism out
Two model generations, and which compat level picks
The cardinality estimator has two generations:
| Model | Compatibility level | Key assumptions |
|---|---|---|
| CE 70 (legacy) | Below 120 | Independence between columns, uniformity within steps, simple containment - the model from SQL Server 7.0 |
| Modern CE (120-170) | 120 and above | Columns correlate; base containment for joins; better on skewed, modern workloads - the model iterated since 2014 |
The compatibility level is the switch. A database at compat 110 runs CE 70 for every query; at compat 160 it runs the current model. When an upgrade regresses a query, the first suspect is the CE model change under a new compat level - the plan changed because the estimates did.
Overrides exist at three granularities, finest first:
- Per query - the
USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION')query hint, or the same enforced via a Query Store hint without touching code. - Per database -
ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = ON, which forces CE 70 while keeping the other optimiser improvements of the higher compat level. - Globally - lowering the compatibility level itself; the bluntest instrument and the one that costs the most, because it also forfeits newer optimiser features for all queries.
The constructs that always estimate badly
These are not bugs; they are the cases where the inputs the estimator needs simply do not exist:
- Functions on the filtered column -
WHERE CONVERT(date, ts) = @dhides the distribution behind the function. Rewrite as a range. - Local variables - the optimiser does not know the variable’s value at compile time and falls back to a fixed guess (see the parameter-sensitivity lesson for the other half of this).
- Table variables - no statistics are kept; estimated as a handful of rows regardless of actual content.
- Column-to-column comparisons - the histogram describes one column against constants, not two columns against each other.
!=andNOT- negation predicates break the containment assumption and estimate poorly.- Stale statistics - the histogram reflects a table that no longer exists. On a fast-growing table, the newest values often sit past the histogram’s range edge and are systematically underestimated (the “ascending key” problem).
Stale versus structural - the two fixes
| Diagnosis | Evidence | Fix |
|---|---|---|
| Stale statistics | Header shows old modification date, estimate drifts from actual on a growing table | UPDATE STATISTICS (possibly WITH FULLSCAN); check the auto-update thresholds on a large table, where the default percent-based trigger updates too rarely |
| Model limitation | Statistics fresh, estimate still far off on a construct in the list above | Rewrite the construct, index the expression, replace the table variable, or force the CE version that estimates the query correctly |
The discipline is to separate these before acting. UPDATE STATISTICS fixes the first and does
nothing for the second; adding an index helps neither when the estimate is structurally wrong. The
right instrument for confirming either is the actual execution plan’s estimated versus actual
rows - the next two lessons put that number to work.
Guided practice
A beginner exercise, worked in a scratch database. The scenario: a table whose newest rows outgrow its histogram - the lesson’s stale-versus-structural distinction, reproduced by hand. Work each step and check yourself before moving on.
- Build a dated table. Create
dbo.readingswith anid, areading_date datetime, and a value column; insert a few thousand rows dated in the past, plus an index onreading_dateso a statistics object exists. Check: a statistics object exists forreading_date. If there is none, the estimator has nothing to read - reread what a statistics object holds; the histogram is built over the first column. - Run a range query inside the histogram. Query
WHERE reading_date >= 'x' AND reading_date < 'y'for dates inside the histogram’s range, with the actual execution plan on; read estimated versus actual rows on the read operator. Check: the two numbers are in the same ballpark - a histogram hit. If yours are wildly apart already, the statistics may be stale from the build itself; runUPDATE STATISTICSand repeat before moving on. - Inspect the statistics object. Run
DBCC SHOW_STATISTICSon the table and read the three parts it returns: header, density vector, histogram. Check: the header’s last-updated time and rows sampled match when you built the table, and the histogram tops out near your newestreading_date. If you cannot say what each part is for, revisit the statistics-object section - the exercise only works if you can read the header. - Push data past the histogram’s edge. Insert a few thousand more rows with dates beyond the histogram’s newest step, then re-run the same range query against the new dates without updating statistics. Check: the estimate now under-reads the actual rows - the ascending-key problem, values past the range edge being systematically underestimated. If the estimate still matched, statistics auto-updated; check the header again and aim the range clearly past the edge.
- Apply the stale fix. Run
UPDATE STATISTICS dbo.readingsand re-run the same query. Check: estimated and actual rows converge again - a stale survey, fixed by re-surveying. If they did not converge, the construct itself is the problem, which is step 6’s point. - Demonstrate the structural case. Run the predicate as
WHERE CONVERT(date, reading_date) = @d, compare estimated to actual, then rewrite it as the equivalent range and compare again. Check: the function-wrapped version estimates badly even though statistics are fresh - structural, not stale - while the range version recovers the histogram. If both looked fine on your small table, the point still stands from the lesson’s list; on real data the gap is what decides the plan.
Check your understanding
Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.
- What are the three parts of a statistics object?
Header (last-updated time, rows sampled, modification counter), density vector (distinctness per
column prefix, used for full-key equality and
GROUP BY), and the histogram (up to 200 steps over the leftmost column). If you could not name them, reread the statistics-object section - everything else hangs off what the histogram covers. - Why does a predicate on the first column estimate better than one on a later column? The histogram covers only the leftmost column of the key. A filter on a later column falls back to the density vector - a weaker signal - so the estimate degrades even though the statistics object exists. If you thought every column gets a histogram, revisit the estimate pipeline.
- Which compatibility level selects each CE generation, and how do you override it per query?
Below compat 120 the database runs the legacy CE 70 assumptions; 120 and above runs the modern
model. Per query,
USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION')- or the same via a Query Store hint without touching code; the scoped-configuration switch forces CE 70 for the whole database while keeping the higher compat level. - Why does a table variable estimate as a handful of rows regardless of its content?
No statistics are kept for it - there is no histogram and no density to read, so the estimator
falls back to a fixed assumption. It is a structural blindness, which is why
UPDATE STATISTICScannot help and replacing the table variable can. Revisit the bad-estimate constructs list if this was new. - Statistics are fresh, yet
WHERE CONVERT(date, ts) = @dstill estimates far off. Stale or structural - and what is the fix? Structural: the function hides the column’s distribution from the histogram, and no refresh changes that. The fix is the rewrite - an equivalent range predicate - or one of the other listed remedies, notUPDATE STATISTICSand not a new index. If you reached for the index, revisit the stale-versus-structural table: the two diagnoses have different fixes, and treating the wrong one wastes the incident.
Where SQL Server sits
How this component relates to the rest of the stack. Items without a link are not covered here yet.
Deployed with
Commonly run alongside
- Windows Failover Clustering