Table bloat estimate
Updates and deletes leave dead rows behind until vacuum reclaims them, and a table can double in size from churn alone. This recipe ranks tables by their dead-tuple overhead.
The task
A table's footprint keeps growing even though row counts stay flat, and it is unclear when vacuum last caught up. Comparing live and dead tuple counts shows what the space is made of.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT relname AS table_name,
n_live_tup,
n_dead_tup,
ROUND(100.0 * n_dead_tup
/ NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_autovacuum
FROM pg_stat_user_tables
WHERE n_dead_tup > 0
ORDER BY n_dead_tup DESC;
Como funciona
pg_stat_user_tables tracks live and dead tuple estimates per table; dead rows are the ones the next VACUUM can clear. A high dead_pct with an old last_autovacuum points at a table autovacuum is not keeping up with, often because a long-running transaction is holding back cleanup. These counters only show pending cleanup, not bloat: after VACUUM the space is free for reuse inside the table but the file stays the same size, and only a rewrite (VACUUM FULL or pg_repack) shrinks it. The pgstattuple variant measures that free space directly.
Variations
PostgreSQL: exact free space per table
PostgreSQL-- needs the pgstattuple extension; exact, but scans the table
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT pg_size_pretty(table_len) AS table_size,
dead_tuple_percent,
free_percent
FROM pgstattuple('public.orders');
SQL Server: low fill / sparse pages
SQL Server-- a low avg_page_space_used_in_percent means half-empty
-- pages (wasted space); forwarded_record_count > 0 on a heap
-- means updated rows moved and left pointers behind.
-- Both columns are NULL in the default LIMITED mode.
SELECT ips.index_id, ips.index_type_desc, ips.page_count,
ips.avg_page_space_used_in_percent,
ips.avg_fragmentation_in_percent,
ips.forwarded_record_count
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'),
NULL, NULL, 'SAMPLED') ips;
Questions that come up
Should I run VACUUM FULL on a bloated table?
VACUUM FULL returns the space to the OS but holds an ACCESS EXCLUSIVE lock for the whole rewrite, blocking reads as well as writes, and needs free disk for a full copy of the table. pg_repack does the rewrite while the table stays in use. To keep it from coming back, tune autovacuum for the hot table, for example ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02).
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.