SQL Server Statistics Guide: Finding and Correcting Bad Row Estimates

SQL Server Statistics Guide: Finding and Correcting Bad Row Estimates

Before SQL Server executes a query, the Query Optimizer compares possible execution plans and attempts to choose one with a low estimated cost. One of the most important inputs to that calculation is the estimated number of rows produced by each operator. SQL Server derives these estimates largely from statistics objects, including their histograms and density information.

If statistics are stale or do not represent the current data distribution, the optimizer can estimate cardinality incorrectly. The resulting plan may use an unsuitable join algorithm, request excessive memory, perform unnecessary sorting, or spill to tempdb. This is related to, but different from, index design: an index can improve data access, while statistics help the optimizer predict how much data will be returned.

What are SQL Server statistics?

A statistics object summarizes the distribution of values in one or more columns. Its histogram represents value distribution across ranges, primarily for the first column in the statistics definition. Density information helps the optimizer reason about how selective predicates may be.

Consider an orders table in which most rows have a Completed status and only a small fraction have Pending. If the optimizer accurately estimates WHERE Status = 'Pending', it may choose a plan optimized for a small result set. If the statistics are old, it may expect many more rows and select a plan designed for a much larger input.

SQL Server can create statistics when an index is created, when automatic statistics creation is enabled, or when an administrator uses CREATE STATISTICS. Automatically created single-column statistics commonly have names beginning with _WA.

Automatic creation and automatic updates

For most databases, a sensible baseline is to keep AUTO_CREATE_STATISTICS and AUTO_UPDATE_STATISTICS enabled. The first option allows the optimizer to create statistics for certain predicate columns that do not already have a suitable histogram. The second allows statistics to be refreshed when SQL Server determines that enough data changes have occurred.

An automatic update does not happen after every modification. SQL Server considers the number of changed rows since the last update together with the table cardinality. Therefore, a small table receiving frequent changes and a very large table receiving periodic bulk loads may cross the update threshold at different times.

With synchronous updates, a query can wait while stale statistics are refreshed; the query is then compiled using current information. With asynchronous updates, a query may initially compile using the existing statistics while the refresh occurs in the background. The appropriate choice depends on workload characteristics and must be validated with measurements.

How to check statistics freshness

Start by verifying that the symptoms are consistent with a statistics problem. A large difference between estimated and actual rows is a useful signal. It is not proof, however. Correlated columns, expressions, implicit conversions, non-sargable predicates, and query design can also produce estimation errors.

The following query helps review the last update time and modification count for statistics objects in the current database:

SELECT
    OBJECT_SCHEMA_NAME(s.object_id) AS schema_name,
    OBJECT_NAME(s.object_id) AS table_name,
    s.name AS statistics_name,
    sp.last_updated,
    sp.rows,
    sp.rows_sampled,
    sp.modification_counter
FROM sys.stats AS s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE OBJECTPROPERTY(s.object_id, 'IsUserTable') = 1
ORDER BY sp.modification_counter DESC;

A high modification_counter does not automatically mean that the statistics must be refreshed immediately. Review the critical queries that use the table, the type of modifications being made, and the I/O and compilation cost of an update. The DMV is evidence for a decision, not a universal threshold.

When should you update statistics manually?

A manual update can be useful after a large bulk load, a major deletion, an archive restore, or another operation that materially changes data distribution. This is particularly relevant when newly loaded values fall outside the ranges that important queries filter on, because automatic thresholds may not be reached before estimates become inaccurate.

To update all statistics for a table:

UPDATE STATISTICS dbo.SalesOrder WITH SAMPLE 30 PERCENT;

To scan every row while building the statistics:

UPDATE STATISTICS dbo.SalesOrder WITH FULLSCAN;

FULLSCAN can be expensive on large tables and may extend a maintenance window. It should therefore be selected based on measured need rather than used as the default for every table every night.

To update statistics across the current database, administrators can use:

EXEC sys.sp_updatestats;

This is a broad operation. Before running it in production, evaluate its duration, tempdb usage, concurrent workload, and the potential for query plan recompilations.

Handling missing or insufficient statistics

Automatic statistics are sufficient for many workloads, but a single-column statistics object cannot represent every relationship between columns. If queries frequently filter by both Region and CustomerType, a multi-column statistics object may improve the optimizer’s understanding of that predicate combination:

CREATE STATISTICS ST_Customer_Region_Type
ON dbo.Customer (Region, CustomerType)
WITH AUTO_DROP = ON;

Column order matters. The histogram is built for the first column, so that column should be chosen with the query patterns and data distribution in mind. A multi-column statistics object is not an index and does not directly accelerate row retrieval.

For workloads that repeatedly query a clearly defined subset, filtered statistics may also be appropriate:

CREATE STATISTICS ST_OpenOrders
ON dbo.SalesOrder (CustomerId)
WHERE Status = 'Open';

The filter must align with the predicates used by relevant queries. Unnecessary manual statistics can increase maintenance and troubleshooting complexity, so each one should have a documented reason and an owner.

Common mistakes to avoid

  • Running FULLSCAN for everything nightly: This can create unnecessary I/O, CPU, and compilation overhead on large systems.
  • Using NORECOMPUTE casually: Disabling automatic updates can allow estimates and plans to deteriorate over time.
  • Explaining every estimation issue with index fragmentation: Physical fragmentation and data-distribution accuracy are separate concerns.
  • Applying one modification threshold everywhere: Table size and the shape of changes both influence whether a refresh is useful.
  • Updating without validating the plan: Current statistics do not guarantee a specific plan; compare actual and estimated rows before and after the change.

A practical maintenance process

  1. Identify critical queries and the tables they depend on.
  2. Track actual-versus-estimated row differences and statistics update times.
  3. After large data loads or distribution changes, update the affected statistics selectively.
  4. Increase the sampling level when evidence supports it; treat FULLSCAN as a measured exception.
  5. Document manually created statistics, their purpose, and their ownership.
  6. Compare CPU time, duration, logical reads, memory behavior, and spills before and after maintenance.

Effective statistics management is based on measurement and data-change patterns rather than indiscriminate maintenance. The goal is not to refresh every statistics object constantly. The goal is to give the optimizer a sufficiently accurate picture of the data for the queries that matter most.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published