VACUUM, ANALYZE, and autovacuum
- Version
- 19
- Review
- Draft
Summary#
VACUUM frees space from obsolete row versions when no transaction needs them, so later writes can reuse that space. ANALYZE refreshes the statistics the planner uses to choose query plans. Autovacuum runs ordinary vacuuming and analysis in the background as tables change, and also vacuums to prevent transaction ID wraparound.
Syntax#
VACUUM table_name;
ANALYZE table_name;
VACUUM ANALYZE table_name;
VACUUM FULL table_name;
Example#
Run psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch PostgreSQL 19 database with autocommit on. The temporary table disappears when psql exits. Autovacuum cannot maintain temporary tables, so the script runs maintenance explicitly. It deletes old rows, refills some freed space without growing the heap, checks the recorded number of distinct zones and then compacts the heap. The output compares sizes because raw byte counts can vary with the server's block size.
CREATE TEMP TABLE parcel_events (id integer, zone integer, payload text);
SET default_statistics_target = 100;
INSERT INTO parcel_events
SELECT n, n % 4, repeat('x', 240) FROM generate_series(1, 4000) AS g(n);
SELECT pg_relation_size('parcel_events') AS loaded_bytes \gset
DELETE FROM parcel_events WHERE id <= 3000;
VACUUM parcel_events;
INSERT INTO parcel_events
SELECT n, n % 4, repeat('y', 240) FROM generate_series(4001, 5000) AS g(n);
SELECT pg_relation_size('parcel_events') = :loaded_bytes AS heap_size_unchanged,
count(*) AS live_rows
FROM parcel_events;
ANALYZE parcel_events;
SELECT n_distinct AS distinct_zones
FROM pg_stats
WHERE schemaname = (SELECT nspname FROM pg_namespace WHERE oid = pg_my_temp_schema())
AND tablename = 'parcel_events' AND attname = 'zone';
VACUUM FULL parcel_events;
SELECT pg_relation_size('parcel_events') < :loaded_bytes AS heap_shrank,
count(*) AS live_rows
FROM parcel_events;
Expected output#
heap_size_unchanged|live_rows
t|2000
(1 row)
distinct_zones
4
(1 row)
heap_shrank|live_rows
t|2000
(1 row)
Common mistakes#
Run VACUUM outside explicit transaction blocks. Ordinary VACUUM generally leaves the space in the table for reuse. It can return empty pages at the end of the table to the operating system, and that truncation requires an exclusive lock. VACUUM FULL writes a new copy and needs spare disk space during the rewrite. It holds ACCESS EXCLUSIVE on the table, blocking even plain SELECT. Autovacuum never runs VACUUM FULL.
Version applicability#
PostgreSQL 9.0 changed VACUUM FULL to rewrite the table and rebuild its indexes. The example needs psql 9.3 or later for \gset, which saves the initial heap size in a client variable. PostgreSQL 19 still accepts VACUUM FULL and deprecates it in favor of REPACK.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0