Tuesday, 8 a.m. The report on Monday's sales takes almost three times longer than usual. Nobody deployed anything, nobody rewrote anything, and the DBA swears nobody so much as breathed on the server.
Same query. Same indexes. The only change: last night's import added 90,000 new orders. And at 8 a.m., SQL Server still doesn't know about them.
Well, the data is there. Its statistics just haven't heard the news. And statistics are what it decides by.
The optimizer is a warehouse manager who never visits the warehouse
#In the previous article, we compared estimated and actual rows in an execution plan. Now let's look at where that estimate comes from.
Before SQL Server runs a query, it has to pick a plan: which index, which join, how much memory. It doesn't look at the data to do that. That would be like sending someone to count every box before each order. Counting would take longer than the order itself.
So it decides based on the last stock count. The stock count says roughly how much of what is in the warehouse. In SQL Server, it's called statistics.
When the count is right, the manager sends one person with a hand truck for three boxes and a forklift for three thousand. When it's wrong, the person with the hand truck goes for three thousand boxes. And then everyone wonders why shipping has stopped.
What statistics are
#A statistics object is a small summary of the values in one or more columns. SQL Server creates these on its own:
- with every index, for its key columns,
- for a column you filter on that has no statistics yet. That happens when
AUTO_CREATE_STATISTICSis on (the default, and please leave it that way). You'll recognize them by names like_WA_Sys_….
Here's how to look inside:
DBCC SHOW_STATISTICS ('dbo.Orders', 'IX_Orders_CustomerId');
The output has three parts: a header (when the statistics were updated, how many rows the table had, and how many were sampled), the density vector, and the histogram. The header is the date of the stock count. The rest is the count itself.
The histogram: a stock count by shelf
#The histogram describes how values are distributed in the first column of the statistics. It has at most 200 steps, even if the table has a hundred thousand customers. Each step is a shelf with a label.
So I wouldn't be writing from memory, I built a test table on my laptop (SQL Server 2022): 10 million orders, 100,000 customers, and one wholesaler, customer 7, with two million orders. The histogram on CustomerId needed just 39 steps. Here are three of them:
RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
7 368 2,000,000 5 73.6
651 51,918 106 643 80.74
1,159 40,327 53 507 79.54
How to read it:
RANGE_HI_KEYis the shelf label, the upper bound of the step.EQ_ROWSis how many rows have exactly that value. Customer 651 has 106 orders.RANGE_ROWSandDISTINCT_RANGE_ROWSdescribe the values between labels. Between customers 7 and 651, there are 643 other customers with 51,918 orders in total.AVG_RANGE_ROWSis the average per value inside the step: 80.74.
The optimizer's estimates are then simple. CustomerId = 651 sits right on a label, so 106 rows. CustomerId = 42 falls between labels, so it gets the step average: 80.74 rows. Customer 42 actually has 80, so that worked out. If it had 3,000, the histogram would have no idea.
And customer 7? Luckily, the wholesaler with two million orders has its own label. The histogram algorithm tries to give its own step to the values that stand out most from their neighbors, so big customers usually get one.
Usually.
Density: an average that lies with a straight face
#The second part of statistics is the density vector. Density is simply 1 / the number of distinct values. A hundred thousand customers give a density of 0.00001. Times ten million rows: the average customer has 100 orders.
Averages are treacherous, though. In a company where the owner makes a hundred million and nine people make forty thousand each, the average salary is over ten million. Statistically correct, practically useless.
Same with orders: a typical customer has around 80, the wholesaler has two million, and the average comes out at 100.
When does the optimizer use the average instead of the histogram? When it doesn't know the value at compile time. A local variable is the classic case:
DECLARE @customerId int = 7;
-- The optimizer can't see the variable's value at compile time, so it estimates the density average
SELECT
Id,
OrderDate,
TotalPrice
FROM dbo.Orders
WHERE CustomerId = @customerId;
Estimate in my test: 104 rows, the average. Reality: over two million. A plan built for a hundred rows gets two million and acts surprised.
(A stored procedure parameter is a different story. There SQL Server does look at the value, but only once. That's the next article.)
When the stock count happens on its own
#SQL Server doesn't recount the warehouse after every box. It counts changes and marks the statistics as out of date once there are enough of them. Since SQL Server 2016 (compatibility level 130 and higher), the threshold for a table with more than 500 rows is:
MIN(500 + 20% of rows, SQRT(1000 × number of rows))
For a table with 10 million rows, that's 100,000 changes. The old rule was just 500 + 20%, which means over two million changes. A table that gets 90,000 new orders a day would wait more than three weeks for a new count.
I tried it: after 100,000 changes, the statistics stayed as they were; after 100,500, they got updated. The table had 10,090,000 rows at that point, so the threshold came out at 100,449.
Two things that are easy to forget:
- The update doesn't happen right away. SQL Server only notices stale statistics when it compiles a query, or runs a cached plan, that uses them. That's when it updates them, and by default the query waits for it.
- The automatic update doesn't count every box. It takes a sample, and for a big table that's a small fraction of the rows. For my 30 million order items, it was 1.5%. That's fine for evenly distributed data. A wholesaler hiding on a single shelf can easily slip through the sample.
Example: 90,000 orders nobody knows about
#Back to Tuesday's report, this time on my test table. The statistics on OrderDate are from Monday morning, so the histogram ends on Sunday, June 23. On Monday night, the import added 90,000 orders and 270,000 order items. That's 10,000 short of the 100,000-change threshold, so the statistics on Orders stayed as they were.
(The statistics on OrderItems updated themselves, by the way. Those 270,000 items are over their threshold of 173,205.)
In the morning, the report runs:
-- How many units of each product were sold on Monday
SELECT
oi.ProductId,
SUM(oi.Quantity) AS [SoldQuantity]
FROM dbo.Orders AS o
JOIN dbo.OrderItems AS oi
ON oi.OrderId = o.Id
WHERE o.OrderDate >= '2024-06-24'
GROUP BY oi.ProductId
ORDER BY [SoldQuantity] DESC;
The optimizer checks the stock count, and Monday isn't in it. What it does about that depends on which cardinality estimator it uses.
The legacy one (compatibility level 110 and lower, or with LEGACY_CARDINALITY_ESTIMATION turned on) guesses one row. The actual plan:
Index Seek (IX_Orders_OrderDate) Estimated rows: 1 Actual rows: 90,000
Index Seek (IX_OrderItems_OrderId) 90,000 executions
Key Lookup (PK_OrderItems) 270,000 executions
Sort → Stream Aggregate → Sort 1.6 MB of memory, both Sorts spilled to tempdb
Duration 1.4 s
For a single order, this would be the perfect plan: find its items through the index and look up the product and quantity for each. For 90,000 orders, it's 90,000 seeks and 270,000 key lookups. The memory for sorting was also sized by the estimate, so neither Sort fit, both spilled to tempdb, and both show a yellow warning in the plan.
Then all it takes is:
UPDATE STATISTICS dbo.Orders;
And on the next run:
Index Seek (IX_Orders_OrderDate) Estimated rows: 108,426 Actual rows: 90,000
Hash Match in batch mode, parallel on 8 threads
Duration 0.49 s
The sample overshot by 20%, but that's good enough to pick a plan. The optimizer no longer sends a hand truck for ninety thousand boxes, and the report is almost three times faster. (To be fair: the new plan burns 3.7 s of CPU on eight threads, the old one 1.4 s on one. On a busy server, that's another discussion.)
Now the new estimator, the default since SQL Server 2014. On the same stale statistics, it estimated 27,000 rows instead of 90,000. That's off by more than a factor of three, yet 27,000 was enough for the same plan as with fresh statistics, and the report finished in 0.44 s before any update. It kind of ruined my punchline. It's still guessing, though. This time it just got lucky.
Where the stock count lies
#Stale statistics are the usual suspect, but not the only one. The optimizer gets it wrong even with a fresh count:
- The newest data. Exactly the example above. Anything newer than the last update is outside the histogram. Typically dates and increasing IDs.
- Skewed data and a small sample. One customer with two million orders among a hundred thousand small ones. If the sample misses it, the histogram buries it in the average.
- A value the optimizer doesn't know. The local variable from the density example. The estimate is the average.
- A function on a column. SQL Server 2022 surprised me here: it estimated
YEAR(OrderDate) = 2024andDATEADD(DAY, 1, OrderDate)almost exactly, but forMONTH(OrderDate) = 6it expected 849,208 rows instead of 2,262,492. The bigger problem with a function on a column is elsewhere anyway: the index can't be used for a seek. That's for the article on SARGability. - Columns that depend on each other. City and postal code, car make and model. Statistics are per column, so the optimizer has to guess how much the conditions overlap.
How old is your stock count?
#-- Age of the statistics on Orders and the number of changes since their last update
SELECT
s.[name] AS [StatisticsName],
sp.[last_updated] AS [LastUpdated],
sp.[rows] AS [Rows],
sp.[rows_sampled] AS [RowsSampled],
sp.[modification_counter] AS [ModificationCounter]
FROM sys.stats AS s
CROSS APPLY sys.dm_db_stats_properties(s.[object_id], s.[stats_id]) AS sp
WHERE s.[object_id] = OBJECT_ID(N'dbo.Orders');
What to look for:
LastUpdatedis older than the last big import: the count doesn't know about the new stock.RowsSampledis a fraction ofRowsand the data is skewed: the sample may have missed the big values.ModificationCounteris close to the threshold: an update is coming soon, possibly right after your report.
Newer versions of SQL Server also show in the actual plan which statistics the optimizer used and how old they were. Look in the properties of the SELECT operator under OptimizerStatsUsage. For Monday's report, it listed IX_Orders_OrderDate with SamplingPercent 100 and ModificationCount 90,000: a count of the whole table, with 90,000 orders added since.
Manual UPDATE STATISTICS
#The automatic update is a good baseline, and you don't want to turn it off. Sometimes, though, you need a count right now:
-- All statistics on the table, sampled
UPDATE STATISTICS dbo.Orders;
-- One statistic, from the whole table
UPDATE STATISTICS dbo.Orders IX_Orders_OrderDate WITH FULLSCAN;
When it makes sense:
- After a big import or delete, before the reports hit the data. An import that ends with
UPDATE STATISTICSis a well-mannered import. - When the sample misses skewed data. That's what
FULLSCANis for, but only on the statistics that need it. It reads the whole table, so don't run it on everything every night "just in case". - As part of regular maintenance. An index rebuild recalculates its statistics from the whole table, by the way; a reorganize doesn't. I'll get back to that in the article on index maintenance.
One warning. After a statistics update, the plans that depend on those statistics recompile on their next run. So when UPDATE STATISTICS "fixes" a slow query, the statistics weren't necessarily the culprit. Maybe the query just finally got a new plan.
UPDATE STATISTICS as a reflex for every slow query is like rebooting your computer: it often helps, and nobody knows why.
Practical checklist
#| Signal | What to do |
|---|---|
| Estimated and actual rows differ by orders of magnitude | Find out which statistics the optimizer used and how old they are |
| The query reads the newest data | Update statistics right after the import, not at night |
RowsSampled is a fraction of Rows on skewed data |
UPDATE STATISTICS … WITH FULLSCAN for that one statistic |
| The filter uses a local variable | Expect the estimate to be the average |
A function on a column in WHERE |
Rewrite the condition as a range |
UPDATE STATISTICS "fixed" the query |
Check whether it was just a new plan |
What to remember
#The optimizer doesn't look at the data. It looks at the statistics: the histogram for specific values, the density for the average, the header for the date. When an estimate in the plan is off by several orders of magnitude, the first question isn't "why is SQL Server so dumb", it's "which stock count was it working from".
The optimizer trusts the stock count more than it trusts you. So make sure the count is right.
In the next article, we'll look at the case where the stock count is fine and the plan still flies one day and crawls the next: parameter sniffing. Spoiler: customer 7 is coming back.
