📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are statistics in SQL Server and how does cardinality estimation use them? Explain histograms and density vectors, when statistics are created and auto-updated, what the cardinality estimator version changes, and the symptoms of stale or misleading statistics.

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.

Mid-Level Theory Intermediate cardinality-estimation execution-plans query-optimiser query-performance sql-server statistics

🎯 Key points

  • A statistics object has a header, a density vector (1/distinct values per column prefix) and a histogram of up to 200 steps on the leading column
  • Auto-created on predicate columns (_WA_Sys_) and with every index
  • Auto-update threshold since compat 130: MIN(500 + 20% of rows, SQRT(1000 × rows)); synchronous unless AUTO_UPDATE_STATISTICS_ASYNC
  • Default sampling can miss skew; use FULLSCAN or a fixed sample, and PERSIST_SAMPLE_PERCENT so auto-updates keep that rate
  • Density vector gives an average: used for local variables, OPTIMIZE FOR UNKNOWN and unknown values, so it misleads on skewed data
  • CE version follows compatibility level: legacy CE 70 assumes independent predicates, new CE 120+ uses exponential backoff
  • Ascending keys and bulk loads leave new rows beyond the last histogram step; update statistics in the load job
  • Monitor estimated vs actual row gaps and sys.dm_db_stats_properties (last_updated, modification_counter, rows_sampled)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 write WHERE 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_ASYNC avoids 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_properties first. A bad plan is usually a bad estimate, and a bad estimate is usually bad statistics."


What's inside a statistics object

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

Keeping statistics useful

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

CE versions

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands where row estimates come from and can link bad plans to statistics.

Green flags

  • Describes histogram, density vector and the 200-step limit.
  • Knows the auto-update threshold changed and that updates are synchronous by default.
  • Explains local variables vs parameters and the ascending-key problem.
  • Uses sys.dm_db_stats_properties and estimated vs actual rows.

Red flags

  • Thinks statistics are the same as indexes.
  • Turns off auto-update to 'stabilise' plans.
  • Has never compared estimated with actual rows.

📚 Learn in depth

1. Why estimates drive everything

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

2. Reading a histogram

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
  • Value equals a step: estimate = EQ_ROWS.
  • Value inside a range: estimate = AVG_RANGE_ROWS.
  • Value after the last step (2026-11-18): the ascending-key problem. Legacy CE often says 1; new CE uses density times rows.

Only the leading column has a histogram. For (CustomerId, OrderDate), the date column has density information only within this object.

3. Density and unknown values

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.

4. When statistics update

  • Modification counter per statistics object (sys.dm_db_stats_properties.modification_counter).
  • Threshold: older behaviour 500 + 20% of rows; compat 130+ uses the lower of that and SQRT(1000 × rows).
  • The update happens when a query that needs the statistic compiles, not in the background, unless async is on.
  • Index rebuilds update the index's statistics with FULLSCAN; reorganise does not.

5. Correlation and the CE model

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.

6. Table variables and other blind spots

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.

Try it yourself

  1. Run DBCC SHOW_STATISTICS on an index and find the density vector and the last histogram step.
  2. Insert 100,000 rows with today's date, query for today, and compare estimated vs actual rows before and after UPDATE STATISTICS.
  3. Compare WHERE CustomerId = 42 with DECLARE @c int = 42; ... WHERE CustomerId = @c and look at the estimates.
  4. Query sys.dm_db_stats_properties for statistics with a high modification_counter relative to rows.
  5. Toggle LEGACY_CARDINALITY_ESTIMATION and compare estimates on a correlated two-column predicate.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Turning off auto-update statistics to avoid recompiles. Why it is wrong: Estimates rot and plans get steadily worse. Instead: Leave it on; use async updates or scheduled updates for control.
  • Mistake: Treating index maintenance as statistics maintenance. Why it is wrong: A rebuild does refresh that index's statistics with a full scan, but reorganise doesn't refresh them at all, and auto-created column statistics are never touched by either. Skipping rebuilds (common and sensible on SSDs) then leaves statistics to auto-update alone. Instead: Run a separate, scheduled statistics job (for example Ola Hallengren's IndexOptimize with @UpdateStatistics = 'ALL' and @OnlyModifiedStatistics = 'Y', or Elastic Jobs on Azure SQL), plus an update at the end of bulk loads.
  • Mistake: Assuming the default sample is good enough everywhere. Why it is wrong: Sampling misses skew on large tables. Instead: Use 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.
  • Mistake: Testing with local variables in SSMS and expecting the app's plan. Why it is wrong: 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.
  • Mistake: Thinking a multi-column index has histograms on every column. Why it is wrong: Only the leading column has a histogram. Instead: Add column statistics where non-leading columns are filtered alone.
  • Mistake: Upgrading compatibility level without a baseline. Why it is wrong: The CE model changes and some queries regress. Instead: Capture Query Store data first and force previous plans for regressions.
  • Mistake: Using table variables for large intermediate results. Why it is wrong: No statistics, so poor estimates downstream. Instead: Use temp tables for more than a few hundred rows.
  • Mistake: Treating heavy skew as a statistics problem that more updates will solve. Why it is wrong: Even perfect statistics give one plan per compile; a value with 1 million rows and one with 10 need different plans. Instead: Use filtered statistics for the skewed subset, PSP optimisation (compat 160), or design the query and indexes so one plan works for both.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions density or selectivity Why: Checks how selectivity drives index choice
    How to answer

    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.

  2. When: Candidate says stale statistics show up as estimated vs actual row gaps Why: Checks they can find the divergence in an actual plan
    How to answer

    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.

  3. When: Candidate mentions nightly loads or date columns Why: Checks a very common real-world cause of morning slowdowns
    How to answer

    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.

🛠 Real-world problems: how you handle them

Morning dashboards slow after nightly import
Situation
An internal reporting API on [Azure SQL, General Purpose, 8 vCores] served sales dashboards to [about 400] staff. A nightly job imported [roughly 300,000] orders for the previous day. Dashboards filtered on the latest day.
Signals
Application Insights showed dependency duration for the dashboard query jumping from [200 ms] to [6 s] between 8 and 10 am, then recovering after lunch. CPU spiked at the same time. No deployment had happened.
Investigation
Query Store showed the same plan id all day, with duration high only in the morning. The actual plan showed an index seek on OrderDate estimating 1 row and returning 300,000, followed by 300,000 key lookups. `DBCC SHOW_STATISTICS` showed the last histogram step was the previous day; `sys.dm_db_stats_properties` showed a modification counter below the auto-update threshold. The database was still on compatibility level 110 (legacy CE).
Resolution
Immediate: ran `UPDATE STATISTICS dbo.Orders IX_Orders_OrderDate WITH FULLSCAN`, which fixed the estimate and the plan within minutes. Long term: added the statistics update as the import job's final step and moved the database to compat level 150 after a Query Store baseline comparison.
Prevention
Import job now updates statistics and logs the duration. An alert fires if the dashboard query's p95 exceeds [1 s]. Compatibility level changes go through a Query Store before/after comparison documented in an ADR.

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.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me