AI Hints
Home›PostgreSQL Tutorial›Partitioning, VACUUM and Statistics
PostgreSQL · Lesson 89 of 120

VACUUM and Autovacuum

Cleaning up dead rows.

⏱ 2 min read▶ Video at 1:20:10🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Remember MVCC? Every update leaves an old, dead row version behind. Vacuum cleans them up, so the space can be reused. Autovacuum does it automatically, in the background.

  • Updates leave dead rows
  • VACUUM cleans
  • Autovacuum

Dead rows, then vacuum

We update every book three times. The pgstattuple extension counts dead row versions exactly. Then vacuum cleans them up. Run it. Thirty dead rows, then zero.

query.sqlsql
CREATE EXTENSION pgstattuple;
UPDATE books SET stock = stock + 1;
UPDATE books SET stock = stock + 1;
UPDATE books SET stock = stock + 1;
SELECT dead_tuple_count FROM pgstattuple('books');

VACUUM books;
SELECT dead_tuple_count FROM pgstattuple('books');
Output
CREATE EXTENSION
UPDATE 30
UPDATE 30
UPDATE 30
 dead_tuple_count
------------------
               30
(1 row)

VACUUM
 dead_tuple_count
------------------
                0
(1 row)

Vacuum facts

Autovacuum runs on its own, so leave it on. Plain vacuum doesn't lock the table. Vacuum full rewrites the table and locks it, so avoid it on busy tables. Busy tables may need autovacuum tuned to run more often.

keyvalue
Autovacuumleave it on
VACUUMno blocking
VACUUM FULLlocks, rewrites
Busy tablestune settings

Summary

Vacuum removes dead row versions, and autovacuum does it for you. Next, statistics and analyze.

Key takeaways
  • Dead rows
  • VACUUM
  • Autovacuum
Next up: Statistics and ANALYZE — how the planner guesses