0
0
PostgresqlConceptBeginner · 3 min read

What is Vacuum in PostgreSQL: Explanation and Usage

In PostgreSQL, VACUUM is a command that cleans up dead rows left behind after updates or deletes to free space and maintain database performance. It helps prevent table bloat and keeps queries running efficiently by reclaiming storage and updating statistics.
⚙️

How It Works

Imagine your database as a big filing cabinet where you keep papers (rows). When you update or delete a paper, the old version doesn't get thrown away immediately; it stays in the cabinet as a "dead" paper. Over time, these dead papers pile up and make it harder to find the current ones quickly.

The VACUUM process is like a cleaning crew that goes through the cabinet, removes these dead papers, and frees up space. This cleaning helps the database stay fast and efficient. Additionally, VACUUM updates internal statistics that help PostgreSQL decide the best way to run your queries.

💻

Example

This example shows how to run a basic vacuum on a table named employees. It cleans up dead rows and updates statistics.

sql
VACUUM employees;
🎯

When to Use

You should use VACUUM regularly on tables that have many updates or deletes to prevent performance issues caused by dead rows. For example, in a busy sales database where orders are frequently updated or canceled, running vacuum helps keep queries fast.

PostgreSQL also has an automatic vacuum process called autovacuum that runs in the background, but sometimes manual vacuuming is needed after large data changes or before heavy reporting.

Key Points

  • VACUUM removes dead rows to free space.
  • It updates statistics for better query planning.
  • Regular vacuuming prevents table bloat and slow queries.
  • Autovacuum runs automatically but manual vacuum can be necessary.

Key Takeaways

VACUUM cleans up dead rows to keep PostgreSQL tables efficient.
It helps maintain good query performance by freeing space and updating stats.
Use VACUUM regularly on tables with many updates or deletes.
Autovacuum runs automatically but manual vacuuming is useful after big changes.