Sobes.tech
Middle

Why is VACUUM needed in PostgreSQL? Explain the difference between VACUUM and VACUUM FULL.

sobes.tech AI

Answer from AI

In PostgreSQL, the VACUUM command is used to clean the database of 'dead' rows that remain after UPDATE and DELETE operations. This is necessary because PostgreSQL uses MVCC (Multi-Version Concurrency Control), and old versions of rows are not deleted immediately to ensure transaction consistency.

VACUUM frees up space, making it available for reuse within the table, but does not reduce the physical size of the files on disk.

VACUUM FULL is a more 'heavy' operation that not only cleans dead rows but also compresses the table, reducing its physical size on disk. However, VACUUM FULL locks the table for writing, which can lead to delays in operation.

Example usage:

VACUUM my_table;          -- regular cleanup
VACUUM FULL my_table;     -- compression and size reduction

It is generally recommended to regularly perform regular VACUUM, and use VACUUM FULL only when necessary to free disk space or after mass deletions.