الانتقال إلى المحتوى
قواعد البياناتQuery Tuning· 6 دقائق للقراءة

The Optimizer Is Guessing: Statistics, Cardinality Estimates and Bad Plans

Row counts in a plan are predictions from sampled, aging statistics and fixed assumptions. When they're wrong, so is every choice built on them.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A morning report sums the orders that arrived since the 1st, per customer. Twenty thousand came in, fewer than the 31,623 changes SQL Server waits for before it refreshes statistics on a 1,000,000-row table. In a test on SQL Server 2022 running the legacy cardinality estimator, the optimizer expected 1 row. It chose 20,000 key lookups and a sort with a 1 MB memory grant that spilled to tempdb: 60,093 reads. After 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

The belief: the optimizer knows how many rows each step of a query will return. The table is right there, after all.

The plan encourages it. Estimated rows appear with decimals, like 6,000.88, which looks like a calculation, not a guess. Simple filters often land almost exactly: in the test, 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

In SQL Server, a statistics object holds a of its first column, with at most 200 steps, plus a density for each prefix of its columns, one divided by the number of distinct values. It's built from a sample or a full scan. In the test, the histogram on 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

SQL Server refreshes statistics automatically once enough rows change: from compatibility level 130, the lower of 500 + 20% of the rows and the square root of 1,000 × rows. For 1,000,000 rows that's 31,623 changes. Microsoft's docs single out ascending columns, such as 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

For a value it can't see at compile time, like a local variable, the optimizer uses the average rows per distinct value instead of the histogram. In the test, 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

The histograms describe one column each, so for 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:

Filter or situation (SQL Server 2022)Estimated rowsActual rows
City = 'Cairo'4,0044,000
Country = 'EG' AND City = 'Cairo', legacy / default estimator401 / 1,2674,000
Status = @s (local variable) vs the literal 'Cancelled'255,000 / 10,0879,929
20,000 orders newer than the statistics, legacy / default1 / 6,00120,000
The same, after UPDATE STATISTICS ... WITH FULLSCAN19,97920,000

PostgreSQL's docs show the same failure with real data: the city and state pair Washington, DC appears in about 0.35% of a ZIP code table, while the per-column frequencies multiply to 0.0027%, an underestimate of two orders of magnitude.

Fix the input, not the plan

SQL
-- 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

Before the update, that query showed 20,006 modifications on every statistics object of the table. Forcing a different plan with a hint would have left them invisible. For correlated columns, PostgreSQL lets you teach the planner the relationship with extended statistics, following the pattern in its docs:

SQL extended_stats.sql
CREATE STATISTICS customers_country_city (dependencies, mcv)    ON country, city FROM customers;ANALYZE customers;

This PostgreSQL example wasn't run for this article. In SQL Server, the simplest fix in the test was to drop the redundant filter: when the city determines the country, City = 'Cairo' alone was estimated at 4,004.

How to apply it in your project

  1. Compare estimates with actualsRun the slow query with the actual plan in SQL Server or EXPLAIN ANALYZE in PostgreSQL, and find the lowest operator where the two numbers diverge.
  2. Check how fresh the statistics areUse sys.dm_db_stats_properties for the last update and modification counter in SQL Server; in PostgreSQL, look at pg_stats for the columns involved and run ANALYZE after large changes.
  3. Fix what the estimator was givenUpdate 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.
  4. Re-check, then consider hintsConfirm 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.

📚 المصادر

  1. Statistics — SQL Server, Microsoft Learn
  2. Cardinality Estimation (SQL Server) — Microsoft Learn
  3. Statistics Used by the Planner — PostgreSQL Documentation
  4. Row Estimation Examples — PostgreSQL Documentation

التعليقات (0)