Middle
205
What is VACUUM in PostgreSQL?
Answer from AI
sobes.tech AI
The process of cleaning up "dead" rows that are created as a result of UPDATE and DELETE operations.
- UPDATE — does not physically delete the old version of the row, but creates a new one.
- DELETE — marks the row as deleted but does not remove it physically.
"Dead" rows occupy space on the disk and can slow down queries.
Main tasks:
- Releasing disk space: Returns the space occupied by "dead" rows to the operating system.
- Updating statistics: Gathers information about data distribution, helping the query optimizer to build more efficient execution plans.
- Preventing transaction ID wraparound: Important for maintaining data integrity. Each transaction is assigned an ID. If the ID overflows, old transactions might be mistakenly perceived as future ones, leading to data loss.
VACUUMcleans up old IDs.
Types of VACUUM:
VACUUM: Cleans "dead" rows and updates statistics (ifNOVACUUMis not specified). Does not return space to the operating system.VACUUM FULL: A more aggressive option. Rewrites the entire table, removing "dead" rows and freeing space. Locks the table during execution.VACUUM FREEZE: Sets thetransaction IDfor "old" rows to a valueOldestXID, preventing their deletion during regularVACUUMand helping to avoid transaction ID wraparound.
Autovacuum:
By default, PostgreSQL has autovacuum enabled. It automatically runs VACUUM and ANALYZE (updates statistics) for tables that have been significantly modified. Its parameters can be tuned for optimal performance.
Usage examples:
-- Regular vacuuming of a table
VACUUM my_table;
-- Vacuuming with full space reclamation
VACUUM FULL my_table;
-- Vacuuming with transaction ID freezing
VACUUM FREEZE my_table;
The importance of regular VACUUM:
Regular vacuuming, either manually or via autovacuum, is critical for maintaining the performance and health of a PostgreSQL database.