Sub topic 8
Updates and deletes create row versions
This chapter assumes you know the heap page layout from the earlier chapters: line pointers, the tuple header, and ctid. It also assumes you know basic transaction semantics (BEGIN, COMMIT, ROLLBACK). By the end you should be able to predict what the page looks like after an UPDATE or DELETE, and read xmin, xmax, and t_ctid to tell why a row version is visible or not.
Rows are immutable versions
PostgreSQL never edits a stored tuple's column data in place. The two commands work like this:
INSERTwrites a new tuple.UPDATEwrites a new tuple with the changed values and marks the old tuple as superseded.DELETEmarks the tuple as removed and writes nothing new.
Each stored tuple is one row version. The logical row you think of as "alice's account" can have several versions in the heap at the same time. This design is called multiversion concurrency control (MVCC). Readers see an older version while a writer creates a newer one, so neither blocks the other.
Two header fields carry the bookkeeping:
xminis the ID of the transaction that created this version.xmaxis the ID of the transaction that deleted, updated, or locked this version. It is0when no such transaction exists.
A third field, t_ctid, points to the newer version of the row. A tuple that has no newer version points to itself.
Watching an UPDATE
Start with a fresh table.
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance numeric);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 200);
SELECT ctid, xmin, xmax, * FROM accounts;Both rows were inserted by one transaction. The output looks like this, with your transaction ID in place of 750:
ctid | xmin | xmax | id | owner | balance
-------+------+------+----+-------+---------
(0,1) | 750 | 0 | 1 | alice | 100
(0,2) | 750 | 0 | 2 | bob | 200Now update alice and inspect the raw page. The pageinspect extension shows every tuple on the page, including versions that ordinary queries hide.
CREATE EXTENSION IF NOT EXISTS pageinspect;
UPDATE accounts SET balance = balance + 50 WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM accounts WHERE id = 1;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));The SELECT shows only the new version, now at a new address:
ctid | xmin | xmax | id | owner | balance
-------+------+------+----+-------+---------
(0,3) | 751 | 0 | 1 | alice | 150The page has three tuples:
lp | t_xmin | t_xmax | t_ctid
----+--------+--------+--------
1 | 750 | 751 | (0,3)
2 | 750 | 0 | (0,2)
3 | 751 | 0 | (0,3)Tuple 1 is the old version. Transaction 751 set its t_xmax, and its t_ctid now points to tuple 3. Tuple 3 is the new version, created by 751, and it points to itself. Tuple 2 (bob) was not touched.
Because the update creates a whole new tuple, it needs free space on a page. Updating one row of a mostly full page may place the new version on a different page, and the ctid then has a different block number.
Watching a DELETE
DELETE FROM accounts WHERE id = 2;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));Bob's tuple is still on the page. The only change is that t_xmax now holds the deleting transaction's ID:
lp | t_xmin | t_xmax | t_ctid
----+--------+--------+--------
2 | 750 | 752 | (0,2)Its t_ctid still points to itself, because there is no newer version. A deleted version differs from an updated one only in that its t_ctid has no successor.
An UPDATE is internally a delete of the old version plus an insert of the new one. That is why both commands produce dead space.
How a query decides what it can see
Every statement runs with a snapshot. A snapshot records which transactions had committed when it was taken. For each tuple the executor asks two questions:
- Did the transaction in
xmincommit, and was it visible to my snapshot? If not, the version does not exist for me yet (or never will). - Is
xmaxzero, aborted, or a transaction my snapshot cannot see as committed? If so, nobody has removed the version from my point of view, and I can see it.
A version is visible only if the answer to the first question is yes and the answer to the second is yes. The following table lists the common combinations.
| `xmin` state | `xmax` state | Visible? |
|---|---|---|
| Committed, in snapshot | 0 | Yes |
| Committed, in snapshot | Committed, in snapshot | No (deleted or replaced) |
| Committed, in snapshot | Committed after the snapshot | Yes (the delete is not yet visible) |
| Committed, in snapshot | Aborted | Yes (the delete was rolled back) |
| Aborted | Any | No (the insert was rolled back) |
| In progress, other session | Any | No (not committed yet) |
Your own transaction is the exception. It sees its own uncommitted inserts, and it does not see tuples it has deleted itself.
Under READ COMMITTED, each statement takes a new snapshot, so Session B's second query sees 150. Under REPEATABLE READ, the snapshot is taken once per transaction, and B would keep seeing 100.
Rollback leaves the versions behind
Aborting a transaction does not rewrite pages. The tuples it created stay where they are, and the transaction's status is recorded as aborted in the commit log (pg_xact). Later readers see that xmin belongs to an aborted transaction and skip the tuple.
BEGIN;
INSERT INTO accounts VALUES (3, 'carol', 300);
ROLLBACK;
SELECT lp, t_xmin, t_xmax
FROM heap_page_items(get_raw_page('accounts', 0));Carol's tuple appears in the page output, but it is invisible to every query. This is why ROLLBACK is fast, even after a large bulk load. The cost moves to cleanup, which a later chapter covers.
Hint bits
Looking up a transaction's status in pg_xact for every tuple would be slow. The first reader that checks a status writes the result into the tuple's t_infomask field as a hint bit. The bits that matter here are:
0x0100:xminis known committed.0x0200:xminis known aborted.0x0400:xmaxis known committed.0x0800:xmaxis invalid, meaning no live deleter exists.
You can see them with SELECT lp, to_hex(t_infomask) FROM heap_page_items(get_raw_page('accounts', 0));. A side effect is that a plain SELECT can dirty a page, because setting a hint bit is a write. This surprises people who see write I/O on a read-only workload right after a bulk load.
Gotchas and common errors
ctid is a location, not an identity
When a row is updated, its ctid changes. After VACUUM FULL or a rewrite, every ctid changes. Never store a ctid as a reference to a row, and never rely on it between transactions. Use a primary key instead.
A non-zero xmax does not always mean deleted
SELECT ... FOR UPDATE, FOR SHARE, and foreign key checks also record the locking transaction in xmax. The tuple header marks it as lock-only (0x0080 in t_infomask). Also, a tuple whose deleter rolled back keeps its old xmax until the status is hinted or the tuple is rewritten. So a visible row can have a non-zero xmax. Check the status, not just the number.
An update of one column still copies the whole row
Changing a single boolean in a 500-byte row writes another 500-byte version. Large values stored out of line (TOAST) are an exception, because an update that leaves them unchanged can reuse the existing TOAST data. The next chapters cover that. Frequent updates to a wide row are still the main reason tables grow faster than their live data.
Bulk updates can double a table
UPDATE big_table SET flag = true without a WHERE clause writes a new version of every row. Until old versions are reclaimed, the table holds both copies. Check pg_relation_size before and after to see this for yourself.
Long transactions keep old versions alive
An old version can only be removed when no snapshot could still need it. One idle-in-transaction session can therefore hold back cleanup for the entire database. Look for old entries in pg_stat_activity (the xact_start column) when a table keeps growing.
Transaction IDs are 32 bits
xmin and xmax are 32-bit numbers that wrap around. PostgreSQL handles this by freezing old tuples, which marks them as visible to everyone. That process belongs to VACUUM, and the next chapter covers it.
What to remember
UPDATEwrites a new tuple and setsxmaxon the old one.DELETEonly setsxmax.t_ctidlinks an old version to its successor. It points to itself when there is no newer version.- Visibility depends on
xmin,xmax, the status of those transactions, and the reader's snapshot. ROLLBACKleaves tuples in place and marks the transaction as aborted.- Dead versions occupy space until pruning and
VACUUMreclaim it.
Exercise
A table has one row, inserted by transaction 900. Transaction 901 runs UPDATE on it and commits. What do t_xmin, t_xmax, and t_ctid look like for the old and the new tuple, assuming the old tuple is at (0,1) and the new one at (0,2)?
Show answer
Old tuple at (0,1): txmin = 900, txmax = 901, tctid = (0,2). New tuple at (0,2): txmin = 901, txmax = 0, tctid = (0,2), because it points to itself when it has no newer version.
Exercise
A session runs BEGIN; DELETE FROM accounts WHERE id = 2; and has not committed. Another session in READ COMMITTED runs SELECT * FROM accounts WHERE id = 2;. Does it see the row? Does the heap page change when the first session later runs ROLLBACK?
Show answer
The second session still sees the row. The deleter has not committed, so its xmax does not hide the tuple from other snapshots. After ROLLBACK, the page contents do not change. The tuple keeps its xmax value, but the transaction is recorded as aborted, so readers ignore that xmax and see the row as live.
Exercise
You run UPDATE t SET n = n + 1 on every row of a 1 GB table, and the table is now close to 2 GB even though the row count did not change. Explain why, and name one thing that could stop the space from being reused soon.
Show answer
Each updated row got a new tuple, and the old versions stay in the pages as dead tuples until pruning or VACUUM reclaims them. A long-running transaction or an idle-in-transaction session holds an old snapshot, so VACUUM cannot remove the old versions and the space cannot be reused.