Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 148/ 160
08. Transactions, Security & Production SQL Administration

Multi-Version Concurrency Control (MVCC) & Table Bloat

See how MVCC enables readers/writers and why dead tuples cause bloat.

AdvancedMVCC · Dead Tuples3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

The database keeps old copies of changed rows so people reading don't have to wait. A cleaner (VACUUM) throws away the old copies later.

Think of it like…

A shared whiteboard where nobody erases: to change something, you write the new version beside it and cross out the old one. Readers keep seeing whichever version was current when they looked. Someone has to come round and wipe the crossed-out entries, or the board fills up.

Where you’ve seen it

A jobs table updates each row's status five times. Every update leaves a dead version, so the table holds six versions per job until VACUUM runs. A forgotten idle in transaction session from yesterday stops VACUUM removing any of them, and the table grows from 2 GB to 30 GB.

Words you’ll hear

Row version (tuple)
One physical copy of a row; UPDATE creates a new one.
Dead tuple
A version no transaction can see any more, waiting for VACUUM.
VACUUM / autovacuum
Reclaims dead tuples for reuse; autovacuum runs it automatically.
Bloat
Space taken by dead or empty space in tables and indexes.

Visual diagram

Loading interactive diagram

Theory & example queries

How MVCC works in PostgreSQL

Each row version records which transaction created it and which deleted or replaced it. A query takes a snapshot and sees only versions that were committed before the snapshot and not yet replaced. That's how a long-running report sees a consistent picture while other sessions keep updating rows.

The price is that UPDATE and DELETE leave dead versions behind. VACUUM, normally autovacuum, scans tables, removes dead versions that no running transaction can still see, and records the free space for reuse. It doesn't usually shrink the file on disk; reusing the space is the goal. Updates that don't change any indexed column and fit on the same page can be HOT (heap-only) updates, which avoid touching indexes at all.

Checking dead rowsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  relname,3  n_live_tup,4  n_dead_tup,5  last_autovacuum6FROM7  pg_stat_user_tables8ORDER BY9  n_dead_tup DESC10LIMIT11  10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative vacuum statistics3 sample rows
Representative vacuum statistics
relnamen_live_tupn_dead_tuplast_autovacuum
events1820000640002026-11-21 08:05:12
orders42500091002026-11-21 09:10:44
sessions980002300NULL

Note: PostgreSQL statistics are approximate and workload-dependent. The values illustrate tables ranked by dead-row count, not a production measurement.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Updates create versions; VACUUM reclaims the old ones once no snapshot needs them.

What causes bloat and how to fix it

The two usual causes: autovacuum can't keep up with a very high update rate (often fixed by making it more aggressive per table), or something holds back the oldest visible snapshot: a long-running query, a session left idle in transaction, an abandoned replication slot, or a standby using hot_standby_feedback. While the oldest snapshot is old, VACUUM can't remove anything newer.

To reclaim disk space from an already bloated table, VACUUM FULL rewrites it but locks it exclusively; pg_repack does the same online. MySQL's InnoDB uses a different design, keeping old versions in undo logs that a purge thread cleans, so long transactions there show up as a growing history list rather than table bloat. The same advice applies: keep transactions short.

Finding what's blocking cleanupQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  pid,3  state,4  xact_start,5  query6FROM7  pg_stat_activity8WHERE9  xact_start < now() - interval '1 hour'10ORDER BY11  xact_start;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative long transaction2 sample rows
Representative long transaction
pidstatexact_startquery
21457idle in transaction2026-11-21 10:15:03SELECT * FROM reports
21902active2026-11-21 10:42:18SELECT account_id, SUM(amount) FROM ledger GROUP BY account_id

Note: This assumes two transactions have remained open for over an hour. PIDs, timestamps and queries are workload-specific and may contain values hidden by privilege settings.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Old transactions here are the usual culprit.

Key takeaway: Keep transactions short and autovacuum healthy; use pg_repack to shrink bloated tables online.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Monitoring

Measure dead tuples

Check n_dead_tup and last_autovacuum in pg_stat_user_tables for the largest and busiest tables.

Focus at this step

pg_stat_user_tables.n_dead_tup

What to watch at this step
Watch
dead vs live ratio
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

MVCC (Multi-Version Concurrency Control) lets readers and writers work at the same time without blocking each other by keeping several versions of a row. In PostgreSQL an UPDATE writes a new row version and marks the old one dead, and a DELETE just marks the row dead. VACUUM later reclaims dead rows. When dead rows pile up faster than they're cleaned, the table and its indexes grow without holding more live data, which is bloat.

Why it matters: MVCC is why a long report doesn't block checkouts, and why a long-running transaction or a misconfigured autovacuum can make a table ten times bigger and much slower. Senior PostgreSQL interviews ask how it works and how to diagnose bloat.

When to reach for it

  • Explaining why reads don't block writes in PostgreSQL
  • Diagnosing tables that keep growing
  • Tuning autovacuum for update-heavy tables

When to avoid or be careful

  • Long-running or idle-in-transaction sessions
  • Disabling autovacuum to "save resources"
  • Running VACUUM FULL on a busy production table during the day

VACUUM vs VACUUM FULL vs pg_repack

VACUUM / autovacuum
Best for: Routine cleanup of dead rows

Strengths: Runs online without blocking reads or writes.

Watch out: Frees space for reuse but rarely shrinks the file.

VACUUM FULL
Best for: Shrinking a badly bloated table in a maintenance window

Strengths: Rewrites the table compactly and returns space to the OS.

Watch out: Exclusive lock for the whole rewrite: the table is unavailable.

pg_repack
Best for: Shrinking bloated tables in production

Strengths: Rewrites online with only brief locks.

Watch out: Extension to install; needs extra disk space temporarily.

Interview signals & numbers to know

When this topic comes up

  • “How does PostgreSQL handle concurrent reads and writes?”
  • “The table is huge but only has a few million rows”
  • idle in transaction
  • Autovacuum tuning
  • Table bloat

Benchmarks & rules of thumb

1 -
new row version per UPDATE in PostgreSQL
0 -
locks readers take against writers
VACUUM FULL -
needs an exclusive lock

Common mistakes & follow-ups

Common interview mistakes

  • Thinking DELETE immediately frees disk space; it only marks rows dead.
  • Leaving a transaction open in a SQL client for hours and stopping cleanup database-wide.
  • Running VACUUM FULL in production and locking the table for its whole duration.

Likely interviewer follow-ups

  • Why doesn't a long SELECT block UPDATEs in PostgreSQL?
  • What prevents VACUUM from removing dead rows?
  • How does InnoDB's MVCC differ from PostgreSQL's?
Interview tip: Explain MVCC with one UPDATE creating a new version, then connect it to bloat and long transactions. Showing the cause-and-effect chain is what separates a senior answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Multi-Version Concurrency Control (MVCC) & Table Bloat with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Understanding, Detecting & Preventing Deadlocks
Next topic
User-Defined Functions (PL/pgSQL / T-SQL) & Control Flow