Junior — Middle
Can you explain how the VACUUM command works in PostgreSQL and what role it plays in database management?
sobes.tech AI
Answer from AI
In PostgreSQL, the VACUUM command is used to clean the database of 'dead' rows that remain after updates and deletes. PostgreSQL uses MVCC (Multi-Version Concurrency Control), so when data is modified, old versions of rows are not immediately removed but are marked as obsolete.
The VACUUM command performs the following tasks:
- Frees up space occupied by obsolete rows so it can be reused.
- Updates statistics for the query planner (in case of VACUUM ANALYZE).
- Prevents the growth of database files.
There are two main types of VACUUM:
- VACUUM — performs cleaning without locking tables for reading and writing.
- VACUUM FULL — reorganizes the table completely, freeing disk space but locking the table during execution.
Example usage:
VACUUM;
VACUUM FULL;
VACUUM ANALYZE;
Regularly running VACUUM is important for maintaining performance and preventing database bloat.