Sub topic 5
What VACUUM does and does not do
This chapter assumes you know basic SQL, can use psql, and understand MVCC row versions and dead tuples from the earlier chapters. It covers what a plain VACUUM changes inside a table, what it leaves alone, and how to read its output.
What VACUUM is for
An UPDATE or DELETE in PostgreSQL does not erase the old row version. It marks the version as no longer current, and the version stays in the table's pages as a dead tuple. VACUUM is the maintenance command that cleans these up.
For each table it processes, VACUUM does five jobs:
- It finds dead tuples that no running transaction can still see.
- It removes the index entries that point to those tuples.
- It frees the tuples' slots in the table pages and records the free space in the free space map (FSM), so later
INSERTandUPDATEstatements can reuse it. - It updates the visibility map, which marks pages where every tuple is visible to everyone. This lets index-only scans skip heap lookups and lets later vacuums skip those pages.
- It freezes old tuples to prevent transaction ID wraparound. A later chapter covers this.
With the ANALYZE option it also refreshes the planner statistics for the table.
VACUUM (VERBOSE, ANALYZE) public.orders;The phases of a vacuum run
Index entries must be removed before the heap slots they point to. Otherwise an index entry could point at a slot that has been reused by a different row. This ordering gives VACUUM its structure.
The memory loop in the diagram matters for large tables. VACUUM keeps the dead tuple IDs in memory, limited by maintenance_work_mem. Autovacuum uses autovacuum_work_mem if it is set. If the list fills up before the scan ends, VACUUM has to stop scanning and process every index before it continues. Each of those extra rounds reads all the indexes again. A table with many indexes and too little memory can spend most of its vacuum time on repeated index passes. PostgreSQL 17 changed the dead-tuple storage to use less memory, but the principle is the same.
Locking: it runs alongside normal work
Plain VACUUM takes a SHARE UPDATE EXCLUSIVE lock on the table. This lock does not conflict with SELECT, INSERT, UPDATE, or DELETE, so applications keep working. It does conflict with:
- another
VACUUMorANALYZEon the same table, - most
ALTER TABLEforms, CREATE INDEXwithoutCONCURRENTLY,LOCK TABLEin stronger modes.
Two practical consequences follow. A long-running vacuum can make a schema migration wait. And if the migration is already waiting, queries behind it can queue up too, because lock requests are served in order.
VACUUM cannot run inside a transaction block. Running BEGIN; VACUUM ...; fails with an error.
What VACUUM does not do
It usually does not shrink the file
Freed space inside a table is reusable, but the file on disk stays the same size. Suppose you delete half of a 10 GB table and then run VACUUM. The table will still be about 10 GB, with roughly 5 GB of free space that new rows can fill.
The one exception is the end of the file. If the last pages in the file are completely empty, VACUUM tries to truncate them and give that space back to the operating system. This truncation:
- needs a brief
ACCESS EXCLUSIVElock, whichVACUUMtries to get and abandons if another session is in the way, - only helps when the empty pages are at the end,
- can be disabled for one run with
VACUUM (TRUNCATE false), or per table with thevacuum_truncatestorage parameter.
Rows that are spread evenly through the file leave empty space in the middle, and nothing is truncated. Returning that space requires a rewrite, which is the subject of the VACUUM FULL chapter.
It does not defragment pages
VACUUM frees the slots of dead tuples inside a page and compacts the live tuples within that page. It does not move live rows from one page to another. A table whose pages are each 30% full stays that way. Many sparse pages cost you more I/O and more cache space for the same amount of data.
It does not shrink indexes much
Index pages that become completely empty can be recycled, and VACUUM does that. A B-tree page that is only partly empty is left as it is. An index can stay bloated after the table has been vacuumed. REINDEX fixes that, and a later chapter covers it.
It cannot remove tuples that someone can still see
VACUUM computes a cutoff from the oldest snapshot that is still in use anywhere in the cluster, including old transactions, replication slots, and prepared transactions. A dead tuple is removable only if it became dead before that cutoff. Otherwise it is "recently dead" and stays. A single long transaction can make vacuum useless for every table in the database, even tables the transaction never touched. The chapter on cleanup blockers covers this in detail.
It does not run itself on a schedule you control
Manual VACUUM is for particular situations: after a large bulk delete, before a benchmark, or while investigating a problem. Day-to-day cleaning is the job of autovacuum, which is the next topic in this tutorial.
Plain VACUUM compared with VACUUM FULL
The two commands share a name but work differently.
| Row | `VACUUM` | `VACUUM FULL` |
|---|---|---|
| How it works | Cleans pages in place | Writes a new copy of the table and its indexes |
| Lock | `SHARE UPDATE EXCLUSIVE`, so reads and writes continue | `ACCESS EXCLUSIVE`, so reads and writes block |
| Returns space to the OS | Only empty pages at the end of the file | Yes, the new file holds only live data |
| Extra disk space needed | Little | Room for a full copy of the table and its indexes |
| Typical use | Routine cleanup | Rare, after major bloat |
Reading VACUUM VERBOSE
The VERBOSE option prints a report per table and per index. The exact wording and layout change between PostgreSQL versions, and PostgreSQL 17 reformatted much of it, so the sample below only illustrates the kind of lines you will see:
INFO: vacuuming "public.orders"
INFO: finished vacuuming "public.orders": index scans: 1
pages: 0 removed, 41872 remain, 41872 scanned (100.00% of total)
tuples: 183204 removed, 2410553 remain, 0 are dead but not yet removable
removable cutoff: 7421903, which was 12 XIDs old when operation ended
index scan needed: 9120 pages from table (21.78% of total) had 183204 dead item identifiers removed
index "orders_pkey": pages: 9411 in total, 0 newly deleted, 0 currently deleted, 0 reusableThese are the lines worth checking:
- index scans. A value above 1 means the dead tuple memory filled up. Consider raising
maintenance_work_memorautovacuum_work_mem. - removed and remain. The first counts what this run cleaned. The second shows the live tuples left.
- dead but not yet removable. A large number here means something is holding back the cutoff. Look for old transactions or replication slots.
- pages removed. A non-zero value means end-of-file truncation succeeded. Zero is normal.
- removable cutoff, and how old it was. A cutoff that is millions of transactions old points to a blocker.
- index lines. If an index has far more pages than you expect, it may need a rebuild.
Run VACUUM (VERBOSE) before and after a change, and compare "dead but not yet removable". Dead tuple counts in pg_stat_user_tables will usually fall after a successful run. They will not fall for tuples that are held by a blocker.
Useful options
| Option | Effect |
|---|---|
| `VERBOSE` | Print a per-table report |
| `ANALYZE` | Update planner statistics after cleaning |
| `PARALLEL n` | Use up to `n` workers to process indexes. Only indexes are parallelized, not the heap scan |
| `INDEX_CLEANUP off` | Skip index vacuuming. Used in emergencies, such as wraparound risk, because it leaves dead index entries behind |
| `TRUNCATE false` | Do not try to cut empty pages from the end of the file |
| `FREEZE` | Freeze all eligible tuples now |
| `DISABLE_PAGE_SKIPPING` | Do not skip pages the visibility map says are clean. Rarely needed |
A practical check
After a large delete, you can see the behavior directly:
SELECT pg_size_pretty(pg_table_size('public.orders')) AS size_before;
DELETE FROM public.orders WHERE created_at < now() - interval '2 years';
VACUUM (VERBOSE) public.orders;
SELECT pg_size_pretty(pg_table_size('public.orders')) AS size_after;Expect size_after to be about the same as size_before unless the deleted rows were at the end of the file. New inserts will fill the freed space before the table grows again.
Exercise
A 20 GB table has had 60% of its rows deleted. You run a plain VACUUM, and afterwards the table is still about 20 GB. Is VACUUM broken? What happened to the space, and what would you need to do to return it to the operating system?
Show answer
VACUUM is working as designed. It removed the dead tuples and recorded the freed space in the free space map, so future inserts and updates will reuse it, but it does not rewrite the table or move live rows between pages. The file shrinks only if the empty pages happen to be at the end, which is unlikely when deleted rows are spread through the table. To return the space to the operating system, rewrite the table with VACUUM FULL (which takes an ACCESS EXCLUSIVE lock and needs room for a full copy) or with an online tool such as pg_repack.
Exercise
VACUUM VERBOSE on a table reports "index scans: 4" and "2,100,000 dead but not yet removable". Name one cause for each number and one action for each.
Show answer
"index scans: 4" means the memory for dead tuple IDs filled up several times, so every index was processed four times. Raise maintenanceworkmem (or autovacuumworkmem for autovacuum) so more IDs fit per pass. "Dead but not yet removable" means the tuples are still visible to some old snapshot, such as a long-running transaction, an abandoned replication slot, or a prepared transaction. Find it with pgstatactivity (backendxmin), pgreplicationslots, and pgprepared_xacts, then end or fix the offender.