SQL Flow Field Guide

Explain estimates with skewed data

Read estimated versus actual rows and connect a cardinality difference to data distribution and statistics.

What you are trying to do

A dashboard is fast for most customers and slow for one large customer. Build a skewed synthetic table in a SQL Server scratch session and inspect actual plans for common and rare values.

Work through it

  1. The insert creates 18,000 rows for customer 1 and one row for each later customer ID. The index creates a histogram on the filter key.
  2. Enable Include Actual Execution Plan and run both aggregate queries. In each plan, compare Estimated Number of Rows with Actual Number of Rows at the access operator and at the aggregate.
  3. Record the input value, estimated rows, actual rows, logical reads, and chosen access path. The common and rare values have very different cardinalities.
  4. Explain how a large estimate error could change join choice, memory grant, or scan-versus-seek cost. A plan difference alone does not prove the optimizer is wrong. Repeat with current statistics and the same compatibility level.
  5. Use Microsoft's cardinality estimation and statistics references to support the diagnosis. Cardinality estimation · Statistics

Check your work

The common value returns 18,000 rows and customer 19999 returns one row. The evidence table contains estimated and actual rows for both executions, plus the plan and IO observations. The learner explains the effect of skew without treating one access operator as universally correct.

Practice SQL

Open in SQL Flow
IF OBJECT_ID('tempdb..#LabSkew') IS NOT NULL DROP TABLE #LabSkew;
CREATE TABLE #LabSkew (RowId int NOT NULL PRIMARY KEY, CustomerId int NOT NULL, Amount int NOT NULL);
;WITH Numbered AS (
    SELECT TOP (20000) CONVERT(int, ROW_NUMBER() OVER (ORDER BY a.object_id, b.object_id)) AS n
    FROM sys.all_objects AS a
    CROSS JOIN sys.all_objects AS b
)
INSERT INTO #LabSkew (RowId, CustomerId, Amount)
SELECT n, CASE WHEN n <= 18000 THEN 1 ELSE n END, n % 100
FROM Numbered;
CREATE INDEX IX_LabSkew_Customer ON #LabSkew (CustomerId) INCLUDE (Amount);
SET STATISTICS IO, TIME ON;
SELECT CustomerId, COUNT_BIG(*) AS MatchedRows, SUM(Amount) AS TotalAmount
FROM #LabSkew
WHERE CustomerId = 1
GROUP BY CustomerId;
SELECT CustomerId, COUNT_BIG(*) AS MatchedRows, SUM(Amount) AS TotalAmount
FROM #LabSkew
WHERE CustomerId = 19999
GROUP BY CustomerId;
SET STATISTICS IO, TIME OFF;
DROP TABLE #LabSkew;

Open a captured execution plan

Knowledge check

Commands in this lesson

Next lesson Find a plan regression in Query Store