Covers SQL Server statistics objects (header, density vector, 200-step histogram), auto-create and auto-update thresholds, sampling, CE versions tied to compatibility level, ascending-key and correlated-predicate problems, and how stale statistics show up in plans.
Statistics describe the distribution of values in one or more columns: a density vector (how many distinct values) and a histogram of up to 200 steps on the leading column. The cardinality estimator combines them with its model assumptions to predict how many rows each operator returns, and every plan choice depends on that number.
Statistics are auto-created on indexes and filtered columns and auto-updated after enough modifications (since compat level 130, roughly SQRT(1000 × rows) for big tables). The CE version follows the database compatibility level.
Stale or sampled statistics show up as big estimated vs actual row gaps, nested loops over huge inputs and spills. The trade-off: fuller, more frequent updates give better plans but cost I/O and trigger recompiles.
"Statistics are the optimiser's picture of the data. Each statistics object has a header with when it was updated and how many rows were sampled, a density vector that gives the average selectivity for each column prefix, and a histogram on the first column with up to 200 steps: for each step the upper bound value, rows equal to it, rows in the range below it, and distinct values in that range. When I write
WHERE State = 'TAS', the cardinality estimator looks up that value in the histogram. When I writeWHERE CustomerId = @localVariable, it can't see the value at compile time, so it uses the density vector instead: an average, which is wrong for skewed data.SQL Server creates statistics automatically on every index and on columns used in predicates, and updates them automatically once enough rows change. Since compatibility level 130 the threshold for large tables is dynamic, about the square root of 1,000 times the row count, so a 100-million-row table updates after roughly 316,000 changes instead of 20 million. Updates are synchronous by default, so the query that trips the threshold waits;
AUTO_UPDATE_STATISTICS_ASYNCavoids that at the cost of one more execution on the old plan. The CE version comes from compatibility level. The newer CE assumes some correlation between predicates and handles ascending keys better, but it's a model, so plans can change when you upgrade.The mistake I see is people adding indexes or hints when the plan is wrong only because statistics are stale or sampled. The classic case is a date column after a nightly load: today's rows sit beyond the last histogram step, the estimate is tiny, and you get nested loops over 400,000 rows. I check
sys.dm_db_stats_propertiesfirst. A bad plan is usually a bad estimate, and a bad estimate is usually bad statistics."
| Part | Contents | Used for |
|---|---|---|
| Header | Last updated, rows, rows sampled, steps | Judging freshness and sample quality |
| Density vector | 1 / distinct values for each column prefix | Unknown values, GROUP BY estimates, multi-column equality |
| Histogram | Up to 200 steps on the leading column: RANGE_HI_KEY, EQ_ROWS, RANGE_ROWS, DISTINCT_RANGE_ROWS | Literal and sniffed parameter values |
| Option | What it does | When it fits |
|---|---|---|
AUTO_CREATE_STATISTICS / AUTO_UPDATE_STATISTICS |
Default on | Always leave on |
AUTO_UPDATE_STATISTICS_ASYNC |
Query doesn't wait for the update | Latency-sensitive OLTP |
UPDATE STATISTICS ... WITH FULLSCAN |
Reads every row | Skewed columns, after bulk loads |
PERSIST_SAMPLE_PERCENT = ON |
Auto-updates keep your sample rate | Large tables where default sampling misleads |
| Multi-column statistics | Density on column combinations | Correlated predicates (Suburb + Postcode) |
| Filtered statistics | Histogram on a subset | Skew within a subset, e.g. active rows |
| Incremental statistics | Per-partition updates | Partitioned tables |
| Legacy CE (70) | New CE (120+) | |
|---|---|---|
| Multiple predicates | Assumes independence (multiply selectivities) | Exponential backoff (assumes some correlation) |
| Ascending key beyond histogram | Often 1 row | Uses density-based estimate |
| Joins | Simple containment | Base containment |
Switch with ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = ON or per query with USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION'). SQL Server 2022 adds CE feedback, which can adjust model assumptions per query through Query Store.
A nightly import added about 300,000 orders dated 'today'. Morning dashboards filtered on OrderDate >= today, estimated 1 row (legacy CE, compat level 110 after a lift-and-shift), and used nested loops with key lookups: 1.1 million logical reads, 6 s. Updating the statistics after the import and moving to compat level 150 dropped it to 14,000 reads and 150 ms.
Checks whether the candidate understands where row estimates come from and can link bad plans to statistics.
Green flags
sys.dm_db_stats_properties and estimated vs actual rows.Red flags
The optimiser costs every alternative from row counts. If the estimate is wrong, the cost model compares the wrong numbers and picks join types, memory grants and parallelism for a different query.
statistics (histogram, density)
|
v
cardinality estimator + model assumptions
|
v
estimated rows per operator
|
v
cost model -> join type, access path, memory grant, DOP
DBCC SHOW_STATISTICS ('dbo.Orders', 'IX_Orders_Date') WITH HISTOGRAM returns rows like:
RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
2026-11-01 0 2104 0 1
2026-11-08 15020 2230 6 2503
2026-11-15 14880 2198 6 2480
Only the leading column has a histogram. For (CustomerId, OrderDate), the date column has density information only within this object.
Density = 1 / number of distinct values. With 50,000 customers, density is 0.00002; for a 10-million-row table the 'unknown' estimate is 200 rows per customer. If one customer has 400,000 orders, a plan compiled for the average is badly wrong for them. This is the root of both local-variable surprises and parameter sniffing.
sys.dm_db_stats_properties.modification_counter).SQRT(1000 × rows).WHERE Suburb = 'Hobart' AND Postcode = '7000': the values are strongly correlated. Legacy CE multiplies selectivities (independence), giving a tiny estimate. New CE applies exponential backoff (most selective × sqrt(next) × ...). Multi-column statistics give density for the pair. CE feedback in SQL Server 2022 can learn that a correlation assumption was wrong for a repeated query.
Table variables have no statistics. Before compat 150 they were estimated at 1 row; table variable deferred compilation (2019+) uses the actual row count at first compile but still has no histogram. Multi-statement TVFs got a fixed guess (1 or 100) until interleaved execution (2017). Temp tables do have statistics.
DBCC SHOW_STATISTICS on an index and find the density vector and the last histogram step.UPDATE STATISTICS.WHERE CustomerId = 42 with DECLARE @c int = 42; ... WHERE CustomerId = @c and look at the estimates.sys.dm_db_stats_properties for statistics with a high modification_counter relative to rows.LEGACY_CARDINALITY_ESTIMATION and compare estimates on a correlated two-column predicate.Inspect, find stale, and fix statistics on an orders table.
-- What the optimiser knows about OrderDate
DBCC SHOW_STATISTICS ('dbo.Orders', 'IX_Orders_OrderDate') WITH STAT_HEADER, HISTOGRAM;
-- Which statistics are stale relative to table size
SELECT
OBJECT_NAME(s.object_id) AS table_name,
s.name AS stats_name,
sp.last_updated,
sp.rows,
sp.rows_sampled,
sp.modification_counter,
CAST(100.0 * sp.rows_sampled / NULLIF(sp.rows, 0) AS decimal(5,1)) AS sample_pct
FROM sys.stats s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp
WHERE OBJECTPROPERTY(s.object_id, 'IsUserTable') = 1
AND sp.modification_counter > SQRT(1000.0 * sp.rows)
ORDER BY sp.modification_counter DESC;
-- After the nightly import: full scan, and keep that sample rate for auto-updates
UPDATE STATISTICS dbo.Orders IX_Orders_OrderDate
WITH FULLSCAN, PERSIST_SAMPLE_PERCENT = ON;
-- Correlated columns: give the optimiser density for the pair
CREATE STATISTICS ST_Customers_Suburb_Postcode ON dbo.Customers (Suburb, Postcode);
-- Latency-sensitive OLTP: don't make the unlucky query wait for the update
ALTER DATABASE CURRENT SET AUTO_UPDATE_STATISTICS_ASYNC ON;
Run the update from the import job itself so the first morning query doesn't pay for it:
namespace Shop.Import;
using Microsoft.Data.SqlClient;
public sealed class PostImportMaintenance(string connectionString)
{
public async Task RefreshOrderStatisticsAsync(CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand(
"UPDATE STATISTICS dbo.Orders IX_Orders_OrderDate WITH FULLSCAN;", conn)
{
CommandTimeout = 600 // full scans on big tables take minutes
};
await cmd.ExecuteNonQueryAsync(ct);
}
}
IndexOptimize with @UpdateStatistics = 'ALL' and @OnlyModifiedStatistics = 'Y', or Elastic Jobs on Azure SQL), plus an update at the end of bulk loads.FULLSCAN or a fixed sample with PERSIST_SAMPLE_PERCENT = ON on skewed columns, so later auto-updates don't fall back to the default rate.DECLARE @c int = 42 is invisible at compile time, so the estimate comes from the density vector, while the app's parameters are sniffed against the histogram. Instead: Test the way the app runs: EXEC sp_executesql N'... WHERE CustomerId = @c', N'@c int', @c = 42; (or call the procedure with parameters), with the app's SET options, and try both a typical and an extreme value.Statistics problems hide behind every other symptom: 'needs an index', 'parameter sniffing', 'tempdb spills'. The senior move is to check estimate accuracy before anything else and to make statistics maintenance an owned, scheduled job tied to data loading patterns, not an afterthought of index maintenance.
On Azure SQL, auto-update stays on and there is no SQL Agent in single databases, so maintenance runs from Elastic Jobs, Azure Automation or the import pipeline itself. Measure with Query Store: plan changes that line up with statistics updates are a strong signal.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Defaults (auto create/update) | Most tables | None | Skewed or ascending-key tables with big loads |
| Async auto-update | Latency-sensitive OLTP | One more run on old plan | Batch jobs that need the new plan immediately |
| Scheduled FULLSCAN | Skewed or critical tables | I/O, minutes on large tables | Tiny tables |
| Update in the load job | Nightly or bulk imports | Lengthens the job | Continuous trickle inserts |
| Filtered / multi-column stats | Correlated or subset skew | Extra objects to maintain | Without a proven bad estimate |
Selectivity is the fraction of rows a predicate returns: OrderId = 5 is highly selective, IsActive = 1 matching 95% of rows is not. Density is 1 / distinct values for a column (or column prefix); a column with 4 statuses has density 0.25.
SQL Server keeps both in statistics: a header, a density vector for each key prefix, and a histogram of up to 200 steps on the leading column. The optimiser uses the histogram for literals and sniffed parameters and falls back to density for local variables and unknown values.
An index on a low-selectivity column is often ignored because a seek plus thousands of key lookups costs more than one scan. Trade-off: such columns are useful as part of a composite or filtered index, rarely alone.
An estimated plan is what the optimiser would do; an actual plan is the same plan plus runtime numbers: actual rows, number of executions, memory grant used and runtime warnings. Data flows right to left; thick arrows mean many rows.
The first thing I check is estimated vs actual rows on each operator: a big gap means a bad estimate, and almost every bad plan follows from one. Then I look for scans where I expected seeks, key lookups executed thousands of times, the join type (nested loops with a huge outer input is a red flag), and warnings such as CONVERT_IMPLICIT, spills and residual predicates.
Cost percentages are estimates too, so I confirm with logical reads from SET STATISTICS IO.
Statistics hold a histogram of at most 200 steps built at the last update. Rows added since then with keys beyond the last step — today's dates, new identity values — are invisible to it. The legacy cardinality estimator (CE) typically estimates 1 row for them; the new CE (compat 120+) assumes the rows exist and estimates from density and the modification counter, which is better but often still low after a big load. The bad estimate cascades: nested loops instead of hash joins, tiny memory grants that spill. I fix it by updating statistics as the last step of the load, watching modification_counter, and using incremental statistics on partitioned tables so the update is cheap.
How to tell it (STAR)
**S:** Our sales dashboards on Azure SQL were slow every morning, around [6 seconds], and fine by afternoon. **T:** I was asked to find out why without a release to blame. **A:** I pulled the query from Query Store, saw the plan hadn't changed, and the actual plan showed an estimate of 1 row against 300,000 actual rows for today's date. The histogram ended at yesterday, because the nightly import added rows below the auto-update threshold, and we were on the legacy CE. I updated the statistics, moved the update into the import job, and later raised the compatibility level after comparing Query Store baselines. **R:** Morning p95 dropped from [6 s] to [150 ms] and logical reads fell by about [98%], and we haven't had the morning slowdown since.
Last updated 23 Nov 2026.