Sub topic 7
Spotting Misestimates in `EXPLAIN ANALYZE`
This chapter assumes you can run SQL with psql, read a basic execution plan, and understand indexes at a conceptual level. The focus is finding places where PostgreSQL expected the wrong number of rows.
Estimated rows versus actual rows
PostgreSQL uses a cost-based planner. Before running a query, the planner estimates how many rows each plan step will produce. It uses these estimates to choose between sequential scans, index scans, join algorithms, and other operations.
EXPLAIN ANALYZE runs the query and adds the observed results to the plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE status = 'pending';A plan node may contain output like this:
Seq Scan on orders (cost=0.00..1887.00 rows=5000 width=32)
(actual time=0.020..8.100 rows=4876 loops=1)The planner estimated 5,000 rows, and the scan returned 4,876. That estimate is close enough that it probably did not affect the plan choice.
The important values are:
| Field | Meaning |
|---|---|
| `rows` | Estimated rows produced by the node |
| `actual rows` | Rows observed while running the node |
| `loops` | Number of times the node ran |
| `cost` | Planner cost estimate, not elapsed time |
| `actual time` | Startup and completion time in milliseconds |
When loops is greater than one, actual rows and actual time are normally reported per loop. For example, actual rows=20 loops=100 means the node produced about 2,000 rows in total.
Finding a serious error
A misestimate is a large difference between estimated rows and actual rows. A useful rough ratio is:
actual rows × loops / estimated rowsA ratio near 1 is healthy. Ratios of 10, 100, or more deserve investigation, especially when they occur near the top of a plan or before a join.
The consequences depend on the direction of the error:
- An estimate that is too small can make PostgreSQL choose nested loops or repeated index lookups for a large result.
- An estimate that is too large can make it choose a hash join or sequential scan when a small index-driven plan would be faster.
- An error early in a plan can multiply through later joins and produce a very poor overall plan.
Trace the error to its source
Start at the first node where estimated and actual rows diverge sharply. Do not begin with the slowest node automatically. A slow upper node may only be reporting damage caused by an earlier estimate.
Check whether statistics are current:
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables
WHERE relname = 'orders';If the table changed substantially, collect statistics and test again:
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE status = 'pending';ANALYZE updates the planner's sample-based statistics. VACUUM ANALYZE also cleans dead row versions before collecting statistics, but it is not automatically a better fix for an estimate problem.
Common causes
Misestimates often come from:
- Statistics that are stale after a large data change.
- A highly skewed column whose sample missed important values.
- Correlated predicates, such as
city = 'Paris' AND zip = '75001', where PostgreSQL treats conditions as more independent than they really are. - Temporary tables that have not been analyzed.
- Partitioned-table statistics that do not represent the queried partitions well.
When one column has many distinct or unevenly distributed values, increase its statistics target and analyze again:
ALTER TABLE orders
ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;For correlated columns, extended statistics can record dependencies:
CREATE STATISTICS addresses_city_zip (dependencies, ndistinct)
ON city, zip
FROM addresses;
ANALYZE addresses;Re-run the same EXPLAIN (ANALYZE) after each change. Compare the estimates, actual rows, chosen plan, and execution time. A better estimate matters when it leads to a better plan, not merely because the numbers look closer.
Exercise
A node estimates 100 rows and reports actual rows=25 loops=40. Is this a small or large misestimate?
Show answer
It is large. The node produced about 1,000 rows in total, which is ten times the estimate.