VACUUM Reclaims Dead Tuples After Updates
Updates and deletes leave dead tuples behind: observe them in pg_stat_user_tables, reclaim space with VACUUM, and tighten the autovacuum scale factor.
Code
-- UPDATE/DELETE only mark old tuples dead: the space waits for VACUUM to reclaim it
CREATE TEMP TABLE metrics (
id integer PRIMARY KEY,
value numeric NOT NULL
);
INSERT INTO metrics SELECT g, g * 1.5 FROM generate_series(1, 1000) g;
-- a wide update and delete produce dead tuples
UPDATE metrics SET value = value * 2 WHERE id % 10 = 0;
DELETE FROM metrics WHERE id % 50 = 0;
-- observe the dead tuple count and the last cleanup time (stats views lag slightly; not exact)
SELECT n_live_tup, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'metrics';
-- manual reclaim: space is marked reusable, reads and writes stay unlocked, the table does not shrink
VACUUM metrics;
-- autovacuum trigger threshold = autovacuum_vacuum_threshold (default 50)
-- + autovacuum_vacuum_scale_factor (default 0.2) × estimated row count
-- the scale factor is the backstop for big tables: a 100k-row table waits for ~20k dead tuples; tighten per table for hot ones
ALTER TABLE metrics SET (autovacuum_vacuum_scale_factor = 0.02);How it works
What runs here is SELECT / INSERT / UPDATE / DELETE / CREATE / ALTER — metrics, generate_series and pg_stat_user_tables are the objects involved.
metrics is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Nothing outside the file is needed: the session-local tables it touches (metrics) are created by the file itself — point it at a scratch database and run the whole thing.
Core lines
SELECT n_live_tup, n_dead_tup, last_vacuum, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'metrics';
INSERT INTO metrics SELECT g, g * 1.5 FROM generate_series(1, 1000) g;
UPDATE metrics SET value = value * 2 WHERE id % 10 = 0;
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `metrics`, `generate_series`, `pg_stat_user_tables` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.