What is the VACUUM command in PostgreSQL?.
Answer from AI
sobes.tech AI
VACUUM is a utility in PostgreSQL that performs cleanup of "dead" tuples (rows) left after UPDATE and DELETE operations.
When an UPDATE or DELETE occurs in PostgreSQL, the old version of the row is not immediately physically removed. Instead, it is marked as "dead." This is related to the implementation of Multi-Version Concurrency Control (MVCC), which allows different sessions to see different versions of data.
Dead tuples occupy space on disk and can reduce query performance because more data needs to be processed during table scans.
VACUUM performs the following actions:
- Reclaiming space: Marks the space occupied by dead tuples as available for reuse for new rows.
- Updating statistics: Can update data distribution statistics, which are important for the query optimizer.
- Preventing transaction ID wraparound: Prevents 32-bit transaction ID wraparound (
xid wraps) when usingVACUUM FREEZE.
There are two main types of VACUUM:
-
VACUUM(lazy vacuum): Frees space that can then be reused within the same data file. It does not reduce the size of the table's data file on disk.-- Simple VACUUM call VACUUM table_name; -- VACUUM for all tables in the current database VACUUM; -- VACUUM with statistics update, but without locking the table VACUUM ANALYZE table_name; -
VACUUM FULL(aggressive vacuum): Rewrites the entire table into a new file, completely removing dead tuples. This frees disk space and can reduce the size of the data file. However,VACUUM FULLrequires an exclusive lock on the table, meaning other operations (read/write) will be blocked during its execution. This makes it less suitable for frequent use on active systems.-- VACUUM FULL VACUUM FULL table_name;
For most systems, it is recommended to regularly use VACUUM or VACUUM ANALYZE (often automated with autovacuum), and to use VACUUM FULL only in exceptional cases when disk space needs to be guaranteed freed and table locking is acceptable.
The autovacuum mode in PostgreSQL is enabled by default and automatically runs VACUUM and ANALYZE processes for tables that exceed certain activity thresholds. This greatly simplifies management of cleanup and statistics.