Part 15 / Topic 6 of 7
VACUUM and autovacuum
VACUUM is the garbage collector: it scans for dead tuples and marks their space reusable:
VACUUM readings;
SELECT pg_stat_force_next_flush();
SELECT pg_sleep(0.2);
SELECT n_live_tup, n_dead_tup,
pg_size_pretty(pg_relation_size('readings')) AS heap_size
FROM pg_stat_user_tables
WHERE relname = 'readings';
VACUUM
pg_stat_force_next_flush
--------------------------
(1 row)
pg_sleep
----------
(1 row)
n_live_tup | n_dead_tup | heap_size
------------+------------+-----------
100000 | 0 | 10208 kB
(1 row)
Dead count: zero. Note what didn't shrink: the file. Plain VACUUM makes space reusable inside the table (future writes fill it) but rarely returns it to the OS — VACUUM FULL does that by rewriting the whole table under an exclusive lock, a last resort, not a routine. In normal life nobody runs VACUUM by hand: autovacuum watches each table's dead-tuple count and triggers itself — the setting to respect, never disable.
Two more duties hide under the same command. VACUUM also updates the visibility map (which Part 17's index-only scans depend on), and it performs freezing: transaction ids are 32-bit, and without periodic freezing of old tuples the counter would wrap around — the infamous wraparound emergency where Postgres eventually forces aggressive vacuums to protect data. You'll likely never see it; you should know the word, because "autovacuum is annoying, let's turn it off" is how people meet it.
The one tuning idea worth carrying: for big, hot tables, make autovacuum run more often (lower autovacuum_vacuum_scale_factor per table), not less — many small vacuums beat one giant one.
🧪 Quick quiz — answer from memory, then check.
- What does plain VACUUM do with dead-tuple space?
- Why must old tuples be frozen eventually?
Show the answers
- Marks it reusable within the table — the file usually keeps its size (VACUUM FULL rewrites and returns space, under an exclusive lock).
- Transaction ids wrap around at 32 bits; freezing marks old tuples as "visible to everyone forever" so the counter can safely reuse ids.
Done here? The practice set for Part 15 — 5 exercises with solutions — is on the part page.