Sub topic 2
Dead tuples: what UPDATE and DELETE leave behind
This chapter assumes you know basic SQL, can use psql, and understand transactions and isolation levels. It also assumes you know what an index is. The previous chapter covered how MVCC keeps old row versions. Here we follow what happens to those versions after an UPDATE or DELETE, and how you can observe it.
What a dead tuple is
A tuple is one physical row version stored in a table page. PostgreSQL never edits a row in place. An UPDATE writes a new tuple and marks the old one as replaced. A DELETE only marks the existing tuple as removed. Nothing is erased at that moment.
A dead tuple is a row version that no current or future transaction can see. Once it is dead, it takes up space and does no useful work. Only VACUUM (or opportunistic page pruning, described below) can reclaim it.
Each tuple header carries two transaction IDs:
xminis the ID of the transaction that created the tuple.xmaxis the ID of the transaction that deleted or replaced it. It is 0 while the tuple is live.
A tuple is visible to a snapshot when its xmin committed before the snapshot and its xmax is either unset or not yet committed as far as the snapshot is concerned. When xmax commits and every snapshot in the system is newer than that commit, the tuple is dead.
Watching UPDATE and DELETE create tuples
You can see the version chain with the hidden system columns ctid (the physical location as page and item number), xmin, and xmax.
CREATE TABLE tuple_demo (id int PRIMARY KEY, note text);
INSERT INTO tuple_demo VALUES (1, 'first');
SELECT ctid, xmin, xmax, * FROM tuple_demo;
UPDATE tuple_demo SET note = 'second' WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM tuple_demo;The first query returns ctid of (0,1). After the update the row has a new ctid, usually (0,2), and a new xmin. The old version still sits at (0,1) in the page. Your queries no longer see it, but it has not gone away.
To confirm that the old version exists, install pageinspect as a superuser and read the raw page.
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('tuple_demo', 0));You should see two line pointers. The first has a nonzero t_xmax and a t_ctid that points to the second, which is the newer version. A chain of t_ctid links like this is called an update chain.
What each statement leaves behind
| Statement | What PostgreSQL does | Dead tuples created |
|---|---|---|
| `INSERT` | Writes one new tuple. | None, unless the transaction rolls back. |
| `UPDATE` | Writes a new tuple and sets `xmax` on the old one. | One per row updated. |
| `DELETE` | Sets `xmax` on the existing tuple. | One per row deleted. |
| Rolled-back `INSERT` or `UPDATE` | The new tuple's creator aborted. | The new tuple is dead at once. |
| `TRUNCATE` | Replaces the table's file. | None. The space is returned immediately. |
Three consequences follow from this table.
- An update of one column rewrites the entire row. Updating a boolean flag on a row with a large
textcolumn still creates a full new tuple. Values stored out of line (TOAST) are not copied unless they change, but the main tuple is. - An update that changes nothing still creates a dead tuple.
UPDATE t SET x = xon a million rows leaves a million dead tuples. - Failed work also costs space. Aborted transactions leave dead tuples behind, so retry loops that fail repeatedly add to the pile.
From recently dead to dead
A deleted tuple does not become removable the instant its xmax commits. An older transaction may still hold a snapshot that needs it. PostgreSQL therefore distinguishes two states:
- Recently dead: the deleting transaction committed, but at least one snapshot is old enough to still see the tuple. It cannot be removed yet.
- Dead: no snapshot can see the tuple. It can be removed.
This is why a long-running transaction matters so much. It holds an old snapshot, keeps tuples in the recently dead state, and prevents cleanup. A later chapter covers this in detail. For now, remember that dead tuples are a function of both what was written and what is still running.
Who removes dead tuples
Two mechanisms clean up, and they work at different levels.
Page pruning happens during ordinary reads and writes. When a backend touches a page that is nearly full and holds removable tuples, it can remove them from the page on the spot. Pruning frees the tuple bodies and leaves a small line pointer behind. It is cheap and local to one page. It does not touch indexes, because that would require scanning them.
VACUUM does the complete job. It scans the table, finds dead tuples, removes the matching index entries, and then marks the heap space reusable. Autovacuum runs this for you in the background. Later chapters cover both.
Pruning is also why dead tuple counts in statistics can drift from the physical state of a page. The statistics collector counts dead tuples when statements run. It does not know when pruning has already cleaned a page.
HOT updates: avoiding index churn
Every index entry points to a heap location. A normal update creates a new tuple at a new location, so every index on the table needs a new entry. Old index entries stay until VACUUM removes them. A table with six indexes gets seven writes for one update.
A heap-only tuple (HOT) update avoids this. It applies when both conditions hold:
- The update changes no column that any index uses.
- The new tuple fits on the same page as the old one.
In that case PostgreSQL writes the new version on the same page and links it to the old one. Indexes keep pointing at the first version in the chain and need no changes. Pruning can later remove the old versions without VACUUM touching indexes at all.
You can check how many of your updates are HOT:
SELECT relname,
n_tup_upd,
n_tup_hot_upd,
round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables
WHERE n_tup_upd > 0
ORDER BY n_tup_upd DESC
LIMIT 10;A low hot_pct on a heavily updated table has two usual causes. Either an indexed column changes often, or pages have no free room. The chapter on fillfactor returns to the second cause.
Seeing dead tuples in statistics
The view pg_stat_user_tables keeps running counts of live and dead tuples. These are estimates, updated as statements finish and refreshed by VACUUM and ANALYZE.
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,
last_vacuum,
last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;Try this on the demo table. Turn off autovacuum for it first so the numbers stay put, then generate churn.
ALTER TABLE tuple_demo SET (autovacuum_enabled = false);
INSERT INTO tuple_demo
SELECT g, 'row ' || g FROM generate_series(2, 10000) AS g;
UPDATE tuple_demo SET note = note || ' v2';
DELETE FROM tuple_demo WHERE id % 2 = 0;
SELECT pg_stat_force_next_flush();
SELECT n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'tuple_demo';Expect roughly 5,000 live tuples and 15,000 dead ones: 10,000 old versions from the update plus 5,000 deleted ones. The function pg_stat_force_next_flush() exists in PostgreSQL 15 and later. On older versions, wait a moment and query again, since statistics arrive with a short delay.
ALTER TABLE tuple_demo RESET (autovacuum_enabled);Re-enable autovacuum afterwards. Leaving it off on a real table is a common and costly mistake.
Edge cases worth knowing
- Rollback leaves dead tuples. A bulk load that fails at 99% leaves nearly all its rows dead. Nothing was visible, but the space is used.
- Dead tuples are not only in tables. Each non-HOT update also leaves dead index entries. Index space is therefore a second source of bloat.
INSERT ... ON CONFLICT DO UPDATEcreates a dead tuple whenever it takes the update path, even if the values are the same.- Dead tuples are not visible to
SELECT count(*), but they cost time. A sequential scan still reads every page that contains them. - Statistics are estimates. After a crash,
n_dead_tupresets, so a table can hold many dead tuples while the counter shows zero. Usepgstattuplewhen you need exact numbers. - A hot standby does not run its own cleanup. It replays the primary's removals, and queries on the standby can conflict with them.
Summary of the mechanism
An UPDATE is an insert plus a delete. A DELETE is a mark. Both leave tuples that stay physically present until no snapshot can see them and a cleanup pass removes them. Until then they occupy space in the table, and in its indexes unless the update was HOT. The next chapter shows how that wasted space adds up to table bloat and why it slows queries.
Exercise
A table has three indexes. You run UPDATE accounts SET last_seen = now() WHERE id = 42, and last_seen is not part of any index. The page holding the row has free space. How many tuples are created, how many index entries are added, and which tuple becomes dead?
Show answer
One new tuple is written, on the same page, as a HOT update. No new index entries are added, because no indexed column changed and the new version fits on the page. The old tuple becomes recently dead once the update commits, and fully dead once no snapshot needs it. Pruning or VACUUM can then remove it.
Exercise
After a bulk UPDATE of a whole table, n_dead_tup reads 0 in pg_stat_user_tables, yet the table has doubled in size on disk. Give two possible explanations and one way to check the real figure.
Show answer
The statistics may not have been flushed yet, or may have been reset by a crash, so the counter lags behind the physical state. Page pruning may also have removed some tuples, though not enough to shrink the file, since pruning does not return space to the operating system. To get an exact figure, run SELECT * FROM pgstattuple('table_name'); after installing the pgstattuple extension.
Exercise
Why does a transaction that is rolled back still affect table size?
Show answer
Every tuple it wrote has an aborted xmin, so no snapshot can ever see it. Those tuples are dead immediately, but they still occupy space in the table until pruning or VACUUM reclaims it.