Sub topic 15
Statistics, Bloat, and Maintaining Indexes
An index is not something you create once and forget. The planner's choices depend on statistics that go stale, and the index itself can grow larger than the data it describes. This chapter assumes you can read EXPLAIN output, know how B-trees and composite indexes work, and understand the write costs covered earlier. Examples use PostgreSQL. Other databases have equivalents, noted where useful.
Why the planner needs statistics
The planner never looks at your data when it plans a query. It consults a summary stored in the system catalog and estimates how many rows each step will return. From those estimates it picks between a sequential scan, an index scan, a bitmap scan, and a join order.
PostgreSQL stores these summaries per column:
- The fraction of
NULLvalues. - The estimated number of distinct values.
- A list of the most common values and their frequencies.
- A histogram of the remaining values, used for range predicates.
- A correlation figure between physical row order and column order.
Table-level counts, such as the number of rows and pages, are kept in pg_class. The planner uses the correlation figure to judge how many random page reads an index scan will cost.
If the summaries are wrong, the cost estimates are wrong. The planner may then ignore a good index, or choose a bad index for a query that needs most of the table.
Refreshing statistics with ANALYZE
ANALYZE samples the table and rewrites these summaries. Autovacuum runs it automatically once enough rows have changed, but you can run it by hand.
ANALYZE orders;
SELECT attname, n_distinct, null_frac, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname IN ('customer_id', 'status');n_distinct is the estimated number of distinct values. A negative value means a fraction of the row count, so -1 means every value is unique.
Run ANALYZE manually after a bulk load, after a large delete, or after a migration that rewrites a column. Autovacuum triggers on a percentage of changed rows, so a big change can still be sitting unanalyzed when your next query runs.
Spotting stale statistics in a plan
Use EXPLAIN ANALYZE, which actually runs the query, and compare estimated rows with actual rows.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;A line such as rows=10 ... actual rows=48210 means the estimate was off by a factor of thousands. Everything above that node in the plan inherits the error. A difference of two or three times is normal. A difference of several orders of magnitude means you should investigate statistics.
Remember that EXPLAIN ANALYZE executes the statement. Wrap INSERT, UPDATE, and DELETE in a transaction and roll it back.
Skewed data and the statistics target
The default sample keeps up to 100 most-common values and histogram buckets per column. On a column with a heavily skewed distribution, such as a status column where 98% of rows are 'closed', a larger sample can improve estimates.
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;Larger targets make ANALYZE slower and the catalog bigger, so raise them for specific columns, not globally.
Correlated columns
By default the planner assumes columns are independent. It multiplies selectivities: if 10% of rows have city = 'Oslo' and 10% have country = 'NO', it estimates 1% for both together, even though every Oslo row is in Norway. PostgreSQL 10 and later let you declare the dependency.
CREATE STATISTICS addr_stats (dependencies)
ON city, country FROM addresses;
ANALYZE addresses;Use this when a multi-column filter is badly underestimated and you have confirmed it with EXPLAIN ANALYZE.
Index bloat
Under PostgreSQL's multiversion design, an UPDATE writes a new row version, and a DELETE only marks a row as dead. Index entries that point to dead versions remain until VACUUM removes them. The space freed this way is reused by later inserts, but it is not normally returned to the operating system.
Bloat is the gap between the space an index occupies and the space it needs. It builds up in these situations:
- Heavy update or delete traffic that outpaces vacuum.
- Long-running transactions, which stop vacuum from removing dead rows that the transaction might still see.
- Indexes on monotonically increasing keys where old ranges are deleted. Pages in the old range become sparse but are never refilled, because new keys always go to the right edge.
- Mass deletes followed by no further inserts in that key range.
A bloated index costs you in three ways. It uses more disk. It occupies more shared buffers and OS cache, which pushes useful pages out. It takes more page reads to scan a range.
The block above is intentionally omitted. See the diagram below.
Measuring bloat
Start with size and usage figures. They are cheap and need no extension.
SELECT indexrelname,
pg_size_pretty(pg_relation_size(indexrelid)) AS size,
idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'orders'
ORDER BY pg_relation_size(indexrelid) DESC;An index that is much larger than a freshly built copy would be is bloated. The pgstattuple extension reports it directly.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_id_idx');A healthy B-tree has avg_leaf_density near 90% for a fresh build, and values that stay well above 50% are usually fine. Persistently low density on a large index is a reason to rebuild.
Vacuum and autovacuum
VACUUM removes dead index entries and marks the space reusable. It also updates the visibility map, which index-only scans rely on. If vacuum falls behind, an index-only scan must visit the table to check row visibility, and the "covering" benefit shrinks.
Autovacuum triggers when dead rows exceed a threshold: autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the row count. The default scale factor is 0.2, so a table with 100 million rows waits for about 20 million dead rows. For large, busy tables, lower it per table.
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_scale_factor = 0.01
);Check whether vacuum is keeping up:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;Rebuilding indexes
When an index is badly bloated, rebuild it. Plain VACUUM will not shrink it.
REINDEX INDEX CONCURRENTLY orders_customer_id_idx;REINDEX ... CONCURRENTLY (PostgreSQL 12 and later) builds a new copy beside the old one, then swaps them, so reads and writes continue. It needs extra disk space for the second copy and takes longer than a plain REINDEX. A plain REINDEX locks out writes to the table for its duration, and locks out reads that would use that index.
A concurrent build can fail partway and leave an invalid index behind. Find and remove these:
SELECT indexrelid::regclass AS index_name
FROM pg_index
WHERE NOT indisvalid;The same applies to CREATE INDEX CONCURRENTLY. An invalid index still receives writes and slows them, but the planner does not use it. Drop it and retry.
Rebuilding is not free and does not always help. If the workload will cause the same bloat again within days, fix the cause, such as a long-running transaction or an autovacuum setting, before scheduling rebuilds.
Finding indexes to remove
Maintenance includes deleting indexes. Every index adds write cost, as covered in the chapter on write costs. pg_stat_user_indexes records how often each index has been scanned since statistics were last reset.
SELECT s.indexrelname,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;The query excludes unique indexes, because they enforce constraints even if no query reads them. Before dropping an index with zero scans, check these things:
- The statistics window is long enough to include monthly or quarterly jobs.
- Replicas are checked separately, since each server keeps its own counters.
- The index does not back a foreign key whose parent-side deletes would otherwise scan the child table.
Drop with DROP INDEX CONCURRENTLY to avoid blocking writes.
Other databases
| Concern | PostgreSQL | MySQL (InnoDB) | SQL Server |
|---|---|---|---|
| Refresh statistics | `ANALYZE` | `ANALYZE TABLE` | `UPDATE STATISTICS` |
| Reclaim index space | `REINDEX CONCURRENTLY` | `OPTIMIZE TABLE` | `ALTER INDEX ... REBUILD` |
| Lighter reorganization | None built in | None built in | `ALTER INDEX ... REORGANIZE` |
| Usage tracking | `pg_stat_user_indexes` | `sys.schema_unused_indexes` | `sys.dm_db_index_usage_stats` |
Details differ by version and edition. Check the documentation for online rebuild support in your version.
A maintenance routine
- Let autovacuum do routine work, and tune its scale factors on your largest, busiest tables.
- Run
ANALYZEby hand after bulk loads and large deletes. - When a query is slow, compare estimated and actual rows before blaming the index.
- Review index sizes and scan counts every few months.
- Rebuild only indexes with measured bloat, using the concurrent form.
- Remove unused indexes after confirming with a long statistics window.
Exercise
After loading 50 million rows into orders with COPY, a query on customer_id runs a sequential scan even though an index exists, and EXPLAIN ANALYZE shows an estimate of 1 row against 40,000 actual rows. What do you do first, and why? Then name one danger of fixing a bloated index on a production table with VACUUM FULL.
Show answer
Run ANALYZE orders; first. The bulk load changed the table faster than autovacuum could refresh statistics, so the planner is working from stale numbers, and the estimate error shows this. Then re-run EXPLAIN ANALYZE and check whether the plan changes. VACUUM FULL takes an exclusive lock that blocks all reads and writes while it rewrites the whole table. REINDEX INDEX CONCURRENTLY rebuilds the index without that blocking.