Sub topic 1
How MVCC keeps old row versions
Prerequisites
This chapter assumes you know basic SQL (SELECT, UPDATE, DELETE, CREATE TABLE), can use psql or another PostgreSQL client, and have a general idea of transactions and isolation. You should also know what an index is.
How MVCC keeps old row versions
PostgreSQL uses multiversion concurrency control (MVCC). Under MVCC, the database keeps more than one version of a row so that readers do not block writers. Each transaction sees a snapshot of the data as it was when the transaction started.
An UPDATE does not overwrite a row in place. It writes a new row version and leaves the old one on disk for transactions that still need it. A DELETE marks the current version as deleted but does not remove it. Each version stores transaction IDs in the hidden columns xmin and xmax, and PostgreSQL uses them to decide which snapshot can see which version.
CREATE TABLE orders (id int PRIMARY KEY, status text);
INSERT INTO orders VALUES (1, 'new');
UPDATE orders SET status = 'shipped' WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM orders;The ctid column shows the physical location of the row. After the update, the visible row has a new ctid, which shows that it was written to a new position.
Dead tuples: what UPDATE and DELETE leave behind
A row version becomes a dead tuple once no running transaction can see it. Dead tuples stay in the table until VACUUM removes them.
| Operation | New row version written | Old version left behind |
|---|---|---|
| INSERT | Yes | No |
| UPDATE | Yes | Yes, becomes dead later |
| DELETE | No | Yes, becomes dead later |
> Note: Every UPDATE copies the whole row, even when you change one column.
What table bloat is and why it hurts
Table bloat is the space that dead tuples occupy, plus free space the table has not returned to the operating system. Bloat causes these problems:
- Sequential scans read more pages to return the same rows.
- Indexes point to more dead entries, which makes index scans slower.
- The buffer cache holds fewer live rows.
- Disk usage grows without a matching growth in data.
Measuring bloat with statistics and pgstattuple
The pg_stat_user_tables view gives estimates of dead rows for each table:
SELECT relname, n_live_tup, n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;For exact figures, use the pgstattuple extension. It reads the whole table, so run it carefully on large tables:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len, dead_tuple_count, dead_tuple_percent, free_percent
FROM pgstattuple('public.orders');Exercise
You run 1000 UPDATEs on one row and never run VACUUM. Roughly how many dead tuples should the table hold, and why?
Show answer
About 1000. Each UPDATE leaves the previous version behind, and VACUUM has not removed any of them. The count in pgstatuser_tables is an estimate that updates after the statistics collector flushes.