The symptom
Before it runs a query, the optimizer estimates how many rows each step will return, using statistics it keeps about the data. It picks the join method, the join order, the index and the memory for sorts and hashes from those numbers. A plan with actual row counts shows both the guess and the truth, side by side. When they differ by a factor of ten or more, everything above that step was chosen for the wrong amount of data.
The wrong estimate is rarely the slow step. It is the reason the slow step was chosen. The query plan viewer marks the operators where estimate and actual disagree. Start from the one deepest in the plan, since errors carry upwards. The examples use a shop schema with 400,000 orders, where one customer owns 40,000 of them and every pending order belongs to that customer.
Diagnose it
Compare estimated and actual rows
PostgreSQL prints both on each line of EXPLAIN ANALYZE: the first rows= is the estimate, the second is what happened.
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders WHERE customer_id = 1 AND status = 'pending';
-> Parallel Seq Scan on orders (cost=0.00..6982.00 rows=164 width=37) (actual rows=1333.33 loops=3)
Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))
Rows Removed by Filter: 132000
In a parallel plan the numbers are per worker, shown by loops; multiply to compare. MySQL shows the same pair in EXPLAIN ANALYZE:
EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'pending';
-> Filter: (orders.`status` = 'pending') (cost=40225 rows=39864) (actual time=0.0628..53.3 rows=4000 loops=1)
-> Table scan on orders (cost=40225 rows=398641) (actual time=0.0516..40.3 rows=400000 loops=1)
Oracle reports them as E-Rows 和 A-Rows when the statement runs with the GATHER_PLAN_STATISTICS hint:
SELECT /*+ GATHER_PLAN_STATISTICS */ COUNT(*)
FROM orders WHERE customer_id = 1 AND status = 'pending';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'));
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers |
| 0 | SELECT STATEMENT | | 1 | | 1 |00:00:00.01 | 2391 |
| 1 | SORT AGGREGATE | | 1 | 1 | 1 |00:00:00.01 | 2391 |
|* 2 | TABLE ACCESS FULL| ORDERS | 1 | 394 | 4000 |00:00:00.01 | 2391 |
In SQL Server, an actual execution plan carries Estimated Number of Rows 和 Actual Number of Rows on every operator.
Check whether the statistics are stale
Statistics describe the table as it was when they were last gathered. Rows added since then are invisible to the optimizer. Here 50,000 newer orders are loaded and queried before the statistics catch up:
CREATE TABLE orders_copy AS SELECT * FROM orders;
ANALYZE orders_copy;
INSERT INTO orders_copy
SELECT order_id + 400000, customer_id, status, order_date + interval '3 years', total, reference
FROM orders WHERE order_id <= 50000;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders_copy WHERE order_date >= '2026-01-01';
-> Parallel Seq Scan on orders_copy (cost=0.00..6153.29 rows=19 width=37) (actual rows=16666.67 loops=3)
Filter: (order_date >= '2026-01-01 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 133333
The newest rows are the usual victims: a query for "today" or "this month" asks about values past the end of what the statistics have seen. Each engine records when statistics were last gathered:
SELECT relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE relname = 'orders_copy';
SELECT s.name, sp.last_updated, sp.rows, sp.modification_counter
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('dbo.Orders');
SELECT table_name, n_rows, last_update
FROM mysql.innodb_table_stats
WHERE database_name = DATABASE();
SELECT table_name, num_rows, stale_stats, last_analyzed
FROM user_tab_statistics
WHERE table_name = 'ORDERS';
Look for filters the statistics cannot describe
Fresh statistics still give wrong answers for some predicates:
- Columns that depend on each other. The optimizer multiplies the selectivity of each condition as if they were independent. In the first example every pending order belongs to customer 1, so the true count is ten times the product.
- Expressions. For a calculation on a column, the optimizer has no histogram and falls back to a fixed guess.
- Skewed joins. A filter on one table that selects a row with far more matches than average in the other.
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders WHERE total * 1.2 > 100;
Seq Scan on orders (cost=0.00..10482.00 rows=133333 width=37) (actual rows=337547.00 loops=1)
Filter: ((total * 1.2) > '100'::numeric)
Rows Removed by Filter: 62453
The estimate of 133,333 is exactly one third of the table: the fixed guess PostgreSQL uses for an inequality it knows nothing about.
Table variables
A SQL Server table variable has no column statistics. Since SQL Server 2019 the optimizer knows how many rows the variable holds when the statement that reads it is first compiled, but it still has to guess how many rows match a filter on it:
SET STATISTICS XML ON;
GO
DECLARE @recent TABLE (OrderId int PRIMARY KEY, CustomerId int);
INSERT INTO @recent SELECT OrderId, CustomerId FROM dbo.Orders WHERE OrderId <= 50000;
SELECT COUNT(*) FROM @recent AS r WHERE r.CustomerId = 1;
On our test server the scan of @recent was estimated at 224 rows and returned 5,000. The same data in a temporary table gets real statistics:
CREATE TABLE #recent (OrderId int PRIMARY KEY, CustomerId int);
INSERT INTO #recent SELECT OrderId, CustomerId FROM dbo.Orders WHERE OrderId <= 50000;
SELECT COUNT(*) FROM #recent AS r WHERE r.CustomerId = 1;
That scan was estimated at 5,000 rows.
Row goals: TOP and LIMIT
When a query asks for only the first few rows, the optimizer plans for stopping early. It assumes matching rows are spread evenly, so it expects to find ten of them after reading a small part of the table. If the matching rows all sit at the far end, it reads nearly everything first:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, total FROM orders
WHERE order_date >= '2025-04-01'
ORDER BY order_id LIMIT 10;
Limit (cost=0.42..47.23 rows=10 width=10) (actual rows=10.00 loops=1)
-> Index Scan using orders_pkey on orders (cost=0.42..29668.45 rows=6338 width=10) (actual rows=10.00 loops=1)
Filter: (order_date >= '2025-04-01 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 394079
The plan walks the primary key in order and throws away 394,079 rows before it finds ten that match. SQL Server marks an operator planned this way with EstimateRowsWithoutRowGoal in the plan XML, next to the reduced estimate.
No statistic tells the optimizer where in the table the matching rows sit, so fresh statistics do not change this plan, and neither does an index on order_date by itself: the primary key walk still looks cheaper. What works is taking away the early stop. Fetch the matching rows first, then sort them:
CREATE INDEX orders_date_idx ON orders (order_date);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
WITH recent AS MATERIALIZED (
SELECT order_id, total FROM orders WHERE order_date >= '2025-04-01'
)
SELECT order_id, total FROM recent ORDER BY order_id LIMIT 10;
Limit (cost=5141.15..5141.17 rows=10 width=20) (actual rows=10.00 loops=1)
-> Bitmap Heap Scan on orders (cost=108.95..4902.10 rows=5745 width=10) (actual rows=5921.00 loops=1)
Recheck Cond: (order_date >= '2025-04-01 00:00:00'::timestamp without time zone)
-> Bitmap Index Scan on orders_date_idx (cost=0.00..107.51 rows=5745 width=0) (actual rows=5921.00 loops=1)
Index Cond: (order_date >= '2025-04-01 00:00:00'::timestamp without time zone)
-> Sort (cost=239.05..253.41 rows=5745 width=20) (actual rows=10.00 loops=1)
Sort Key: recent.order_id
Sort Method: top-N heapsort Memory: 25kB
-> CTE Scan on recent (cost=0.00..114.90 rows=5745 width=20) (actual rows=5921.00 loops=1)
Fix it
Refresh the statistics
This is the first thing to try and it is cheap. It fixes stale statistics and nothing else.
ANALYZE orders_copy;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders_copy WHERE order_date >= '2026-01-01';
Seq Scan on orders_copy (cost=0.00..9437.00 rows=45144 width=37) (actual rows=50000.00 loops=1)
Filter: (order_date >= '2026-01-01 00:00:00'::timestamp without time zone)
Rows Removed by Filter: 400000
UPDATE STATISTICS dbo.Orders;
ANALYZE TABLE orders;
EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');
If a table goes stale again and again, the automatic refresh is too slow for it. In PostgreSQL lower autovacuum_analyze_scale_factor for that table; in SQL Server check AUTO_UPDATE_STATISTICS。 statistics staleness snippet lists every table that is behind.
Tell the optimizer about related columns
PostgreSQL extended statistics record how columns depend on each other:
CREATE STATISTICS orders_customer_status_stx (dependencies, mcv)
ON customer_id, status FROM orders;
ANALYZE orders;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders WHERE customer_id = 1 AND status = 'pending';
-> Parallel Seq Scan on orders (cost=0.00..6982.00 rows=1650 width=37) (actual rows=1333.33 loops=3)
Filter: ((customer_id = 1) AND ((status)::text = 'pending'::text))
Rows Removed by Filter: 132000
Oracle has the same idea as a column group. Ask for a histogram on the group, since the point is that some combinations are far more common than others:
SELECT DBMS_STATS.CREATE_EXTENDED_STATS(USER, 'ORDERS', '(customer_id, status)') FROM dual;
EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS', method_opt => 'FOR ALL COLUMNS SIZE AUTO FOR COLUMNS (customer_id, status) SIZE 254', no_invalidate => FALSE);
SELECT /*+ GATHER_PLAN_STATISTICS */ COUNT(*)
FROM orders WHERE customer_id = 1 AND status = 'pending';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'));
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers |
| 0 | SELECT STATEMENT | | 1 | | 1 |00:00:00.01 | 2391 |
| 1 | SORT AGGREGATE | | 1 | 1 | 1 |00:00:00.01 | 2391 |
|* 2 | TABLE ACCESS FULL| ORDERS | 1 | 3300 | 4000 |00:00:00.01 | 2391 |
MySQL: add a histogram
MySQL keeps value distributions only for indexed columns unless you ask. For a filter on a column without an index it assumes a fixed share of the table, which is where the 39,864 above came from: a tenth of the rows. A histogram gives it the real distribution:
ANALYZE TABLE orders UPDATE HISTOGRAM ON status WITH 16 BUCKETS;
EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'pending';
-> Filter: (orders.`status` = 'pending') (cost=40266 rows=4001) (actual time=0.0607..52.8 rows=4000 loops=1)
-> Table scan on orders (cost=40266 rows=399054) (actual time=0.0517..40.4 rows=400000 loops=1)
Make the expression something statistics can cover
Rewrite the condition so the bare column is compared with a value (total > 100 / 1.2 而不是 total * 1.2 > 100). When the expression has to stay, PostgreSQL gathers statistics for an expression that has an index on it or its own CREATE STATISTICS entry:
CREATE STATISTICS orders_total_gross_stx ON (total * 1.2) FROM orders;
ANALYZE orders;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT * FROM orders WHERE total * 1.2 > 100;
Seq Scan on orders (cost=0.00..10482.00 rows=336075 width=37) (actual rows=337547.00 loops=1)
Filter: ((total * 1.2) > '100'::numeric)
Rows Removed by Filter: 62453
When to leave it alone
An estimate that is off by a factor of two or three rarely changes the plan. A large miss also does not matter when the plan would be the same either way: a scan of a table that has to be scanned, or a wrong estimate on the last step with nothing above it. Chase a bad estimate when a join method, a join order or a memory grant above it looks wrong for the real row count.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Capture a plan with actual row counts, not an estimated plan.
- Find the deepest operator where estimated and actual rows differ by ten times or more.
- Check when statistics on that table were last gathered and how many rows changed since.
- Refresh the statistics and capture the plan again.
- If it is still wrong, look for related columns, an expression, a table variable or a TOP/LIMIT.
- Add extended statistics, a histogram or an index that fits the filter.
- Confirm the estimate moved and the plan above it changed.
Questions that come up
How far off does a row estimate have to be to matter?
A factor of ten is a common working threshold. What matters is whether the error crosses a point where the optimizer would choose differently: a nested loop planned for 10 rows that receives 100,000, or a sort given memory for 1,000 rows that receives a million.
Why is the estimate wrong when statistics are up to date?
Because statistics describe one column at a time. Two filters on related columns, a calculation on a column, or a join to a row with far more matches than average all produce wrong estimates from correct statistics. Extended statistics, histograms and rewriting the expression address those cases.
Why does the estimate say 1 row?
Usually the query asks for values outside the range the statistics have seen, such as rows newer than the last statistics refresh. The optimizer concludes almost nothing matches. Refreshing the statistics fixes it.
Are table variables always estimated at one row?
Not since SQL Server 2019. With compatibility level 150 or higher, the statement that reads a table variable is compiled after the variable is filled, so the optimizer knows its row count. It still has no statistics on the columns, so filters and joins on the variable are guessed. A temporary table has full statistics.
What is a row goal?
It is the optimizer planning for a query that will stop after a fixed number of rows, because of TOP, LIMIT, FETCH FIRST or EXISTS. It scales its estimates down to the rows it expects to read before stopping. When matching rows are not spread evenly, it can read far more than planned.