Measure table and index bloat with pgstattuple
PostgreSQLMaintenanceCommand
CREATE EXTENSION IF NOT EXISTS pgstattuple;
-- Fast estimate: skips pages marked all-visible in the visibility map
SELECT pg_size_pretty(table_len) AS table_size,
round(approx_tuple_percent::numeric, 1) AS live_pct,
round(dead_tuple_percent::numeric, 1) AS dead_pct,
round(approx_free_percent::numeric, 1) AS free_pct
FROM pgstattuple_approx('orders');
-- Exact measurement: reads the whole table
SELECT pg_size_pretty(table_len) AS table_size,
round(dead_tuple_percent::numeric, 1) AS dead_pct,
round(free_percent::numeric, 1) AS free_pct,
pg_size_pretty(dead_tuple_len + free_space) AS reclaimable
FROM pgstattuple('orders');
-- B-tree indexes: leaf density (~90 when freshly built; below 50 is bloated)
WITH idx AS MATERIALIZED (
SELECT i.indexrelid
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_am am ON am.oid = c.relam
WHERE am.amname = 'btree' AND i.indrelid = 'orders'::regclass
)
SELECT idx.indexrelid::regclass AS index_name,
pg_size_pretty(s.index_size) AS index_size,
s.avg_leaf_density,
s.leaf_fragmentation
FROM idx
CROSS JOIN LATERAL pgstatindex(idx.indexrelid) s;What it does
Shows the live/dead tuple and free space percentages of a table (fast estimate and exact) and the reclaimable space; for B-tree indexes, leaf density and fragmentation.
When to use it
When the n_dead_tup estimate in pg_stat_user_tables is not enough; to back a pg_repack, VACUUM FULL or REINDEX decision with data.
Caution
pgstattuple and pgstatindex read the whole relation and generate heavy I/O on large tables (they take only AccessShareLock). Use pgstattuple_approx first. By default superuser or the pg_stat_scan_tables role is required. Some free space is normal (fillfactor, room for HOT updates); VACUUM makes it reusable but does not shrink the file; reclaiming it requires pg_repack or VACUUM FULL (ACCESS EXCLUSIVE lock!). Rebuild an index with low avg_leaf_density using REINDEX CONCURRENTLY.