
The Optimizer Is Guessing: Statistics, Cardinality Estimates and Bad Plans
- كاتب موثّق
محتويات المقال
UPDATE STATISTICS it expected 19,979 rows and scanned a covering index instead: 10,398 reads, no spill. The default estimator did better without the update, and still guessed 6,001.
The common misconception
City = 'Cairo' was estimated at 4,004 rows and returned 4,000. And plan regressions get blamed on the optimizer being clever in the wrong way, not on what it was told. But nothing is counted before execution. Every number is a prediction from a summary.
What actually happens
Statistics are a small summary
CreatedAt described 1,000,000 rows in 2 steps, which worked only because the values were evenly spread. PostgreSQL keeps most common values and histogram bounds per column, 100 entries by default, and its docs say the statistics are always approximate, even when freshly updated. From these the optimizer computes a for every operator, and costs every plan on top of them.
Statistics age between updates
IDENTITY or timestamps: new rows land above the histogram's last step, and queries on the newest data get poor estimates. The legacy estimator assumed nothing was there. Since SQL Server 2014, the estimator assumes ascending data may exceed the recorded maximum, which is why it guessed 6,001 rather than 1.
Unknown values get the average
Status = 'Cancelled' was estimated at 10,087 rows, close to the 9,929 it returned. The same filter through a local variable was estimated at 255,000: a quarter of the table's rows, because Status has four values. Parameters are different, and the next article covers what they bring.
Combined filters rely on assumptions
Country = 'EG' AND City = 'Cairo' the optimizer has to combine two selectivities. PostgreSQL's planner and SQL Server's legacy estimator assume the filters are independent and multiply them. Since SQL Server 2014, the default assumes partial correlation, damping the less selective filter. Every Cairo customer is in Egypt, so the truth is full correlation:
City = 'Cairo' | ||
Country = 'EG' AND City = 'Cairo', legacy / default estimator | ||
Status = @s (local variable) vs the literal 'Cancelled' | ||
UPDATE STATISTICS ... WITH FULLSCAN |
Fix the input, not the plan
-- 20,000 new orders since the last statistics updateSELECT CustomerId, COUNT(*) AS n, SUM(Total) AS tFROM dbo.OrdersWHERE CreatedAt >= '2026-11-01 00:00:01'GROUP BY CustomerId;-- Tested, legacy estimator: 1 row estimated, 20,000 read-- through key lookups, sort spilled to tempdb, 60,093 reads-- How stale are the statistics behind the estimate?SELECT s.name, p.last_updated, p.rows, p.modification_counterFROM sys.stats AS sCROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS pWHERE s.object_id = OBJECT_ID('dbo.Orders');UPDATE STATISTICS dbo.Orders IX_Orders_CreatedAt_Id WITH FULLSCAN;-- Tested: 19,979 rows estimated for 20,000; no lookups, no spillCREATE STATISTICS customers_country_city (dependencies, mcv) ON country, city FROM customers;ANALYZE customers;City = 'Cairo' alone was estimated at 4,004.
How to apply it in your project
Compare estimates with actuals Run the slow query with the actual plan in SQL Server or EXPLAIN ANALYZEin PostgreSQL, and find the lowest operator where the two numbers diverge.Check how fresh the statistics are Use sys.dm_db_stats_propertiesfor the last update and modification counter in SQL Server; in PostgreSQL, look atpg_statsfor the columns involved and runANALYZEafter large changes.Fix what the estimator was given Update statistics after big loads, replace local variables with parameters or literals, and remove filters another one already implies. In PostgreSQL, add extended statistics for correlated columns. Re-check, then consider hints Confirm the new estimate in the actual plan. Use a hint only for the queries where the data really breaks the model, and document why.
Key takeaways
The optimizer predicts row counts from sampled statistics; it never counts before it picks a plan. SQL Server refreshes statistics only after enough changes: 31,623 for a 1,000,000-row table, so the newest rows are often invisible. Local variables get an average estimate: 255,000 for a value that matched 9,929 rows in the test. Correlated filters break the independence assumption: 401 or 1,267 estimated for 4,000 actual Cairo customers. Find the first operator where estimates and actuals diverge, then fix its statistics or the query, not the plan.
التعليقات (0)