Sub topic 5
What INSERT, UPDATE and DELETE do to row versions
This chapter assumes you can run psql in two sessions and know what a transaction is. It also assumes you have met the hidden columns xmin, xmax and ctid, which the previous chapter introduced. Here you will see how each write statement creates or marks row versions, and why none of them edits a row in place.
The core rule: versions are never edited in place
PostgreSQL stores each version of a row as a tuple in a heap page. A write statement does not overwrite a tuple. It does one or both of two things:
- It writes a new tuple and stamps its
xminwith the current transaction ID. - It stamps the
xmaxof an existing tuple with the current transaction ID.
Whether another transaction can see a tuple is decided later, from these stamps and from commit status. A writer only records what it did. This is why readers and writers do not block each other.
| Statement | New tuple written | Old tuple's `xmax` set |
|---|---|---|
| INSERT | Yes | No old tuple |
| DELETE | No | Yes |
| UPDATE | Yes | Yes |
INSERT
An INSERT writes one new tuple. Its xmin is the inserting transaction's ID and its xmax is 0.
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
SELECT xmin, xmax, ctid, * FROM accounts;The result shows the transaction ID in xmin, 0 in xmax, and a ctid such as (0,1). That means page 0, item 1.
If the inserting transaction rolls back, the tuple stays on the page. Nothing removes it at rollback time. The transaction is recorded as aborted, so no snapshot will ever treat the tuple as visible. Later, VACUUM reclaims the space. A rolled-back INSERT therefore still consumes heap space until vacuum runs.
DELETE
A DELETE does not remove anything. It sets xmax on the current tuple to the deleting transaction's ID.
BEGIN;
DELETE FROM accounts WHERE id = 1;
-- In this session the row is already invisible.
SELECT count(*) FROM accounts;In a second session, the row is still visible while the first transaction is open. The second session sees a tuple whose xmax belongs to a transaction that has not committed, and it treats that deletion as not having happened.
After the first session commits, new snapshots no longer see the tuple. The tuple remains on the page as a dead tuple until vacuum removes it.
UPDATE
An UPDATE is a DELETE of the old version plus an INSERT of the new version, performed together. Both halves use the same transaction ID.
BEGIN;
SELECT pg_current_xact_id();
UPDATE accounts SET balance = 90 WHERE id = 1;
SELECT xmin, xmax, ctid, * FROM accounts;
COMMIT;The visible row now has xmin equal to the ID you just printed. Its ctid differs from before, because the new version occupies a different item slot. Often that is a different slot on the same page. It can be on another page if the first page has no room.
The same happens even if you update a column to the value it already has. UPDATE accounts SET balance = balance still writes a full new tuple. PostgreSQL does not skip updates that change nothing, unless you add a WHERE condition such as WHERE balance IS DISTINCT FROM 90.
Seeing both versions with pageinspect
The accounts row now has two tuples on the page. Ordinary queries only show the visible one. The pageinspect extension shows both.
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));Creating the extension needs superuser rights by default. Expect output along these lines, with different numbers on your system:
| lp | t_xmin | t_xmax | t_ctid |
|---|---|---|---|
| 1 | 748 | 749 | (0,2) |
| 2 | 749 | 0 | (0,2) |
Read the rows this way:
- Tuple 1 is the old version. Its
t_xmaxis 749, the updating transaction. - Tuple 1's
t_ctidpoints to(0,2), the newer version. - Tuple 2 is the new version. Its
t_ctidpoints to itself, and itst_xmaxis 0.
Following t_ctid from an old version to a newer one is how PostgreSQL walks an update chain. The last tuple in a chain points to itself.
Why the old version must stay
Another transaction may have started before the update committed. Its snapshot was taken earlier, so it must still see balance = 100. If PostgreSQL had overwritten the old tuple, that transaction would see the wrong data or would have to be blocked.
Keeping the old tuple until no snapshot can need it is the entire MVCC design. The price is that every UPDATE and DELETE leaves a dead or soon-to-be-dead tuple. Later chapters cover how vacuum reclaims them.
xmax is also used for row locks
xmax does not always mean "deleted". Statements such as SELECT ... FOR UPDATE and SELECT ... FOR SHARE lock a row by writing the locker's transaction ID into xmax. Infomask bits on the tuple header tell the reader whether xmax means a delete or only a lock.
You can observe this:
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
SELECT xmin, xmax, ctid, * FROM accounts;
-- xmax is now nonzero, but the row was not deleted.
ROLLBACK;Two consequences follow:
- A nonzero
xmaxalone does not tell you the row is dead. You also need the commit status of that transaction and the lock-versus-delete flag. - Locking a row is a write to the heap page. A
SELECT ... FOR UPDATEon many rows dirties many pages, even though no data changed.
When several transactions lock the same row, for example with FOR SHARE, xmax holds a MultiXact ID instead of one transaction ID. This is a separate counter that stands for a group of transactions.
What happens to indexes
An index entry points to a tuple by its ctid. When an UPDATE writes a new tuple at a new location, each index on the table normally needs a new entry pointing to it. The old entries keep pointing to the old tuple until vacuum cleans them.
This is why updates are more expensive on tables with many indexes. A later chapter on HOT updates explains the case where PostgreSQL can avoid the new index entries.
Common mistakes
- Expecting DELETE to shrink the table. A delete only marks tuples. File size stays the same until vacuum frees space inside pages, and in most cases the file does not shrink even then. Only
VACUUM FULLor a rewrite returns space to the operating system. - Assuming a rolled-back transaction leaves no trace. Its inserted and updated tuples remain as dead space.
- Using
ctidas a stable row identifier. Each UPDATE changes it, and vacuum can move or reuse slots. Use the primary key. - Running a mass UPDATE casually. Updating every row in a table writes a full second copy of the table. Plan for roughly double the space until vacuum runs.
- Treating
xmax = 0as proof the row is current. It is only part of the check. The full visibility rules also consider commit status and the snapshot, which the next chapters cover.
Try it yourself
Use a scratch table so you can repeat the experiment. Run the statements in this order and run the heap_page_items query after each step:
- Insert one row.
- Update it once.
- Delete it and commit.
After step 3, the page still holds both tuples. The last one has a committed t_xmax, so no new snapshot sees it, but it remains until vacuum runs.
Exercise
A table has one visible row with xmin 800 and xmax 0. Transaction 805 runs an UPDATE on it and commits. Describe the two tuples on the heap page afterwards, including xmin, xmax and where the old tuple's t_ctid points.
Show answer
The old tuple keeps xmin 800 and now has xmax 805. Its tctid points to the new tuple's location. The new tuple has xmin 805 and xmax 0, and its tctid points to itself. The old tuple is not removed. It stays as a dead tuple until no snapshot can see it and vacuum reclaims it.
Exercise
Session A runs BEGIN; SELECT FROM accounts WHERE id = 1 FOR UPDATE; and stays open. Session B runs SELECT FROM accounts WHERE id = 1. Does B block, and what does xmax on the tuple mean here?
Show answer
B does not block, because a plain SELECT takes no row lock and reads the tuple according to its snapshot. The tuple's xmax holds session A's transaction ID, but it marks a row lock, not a delete. Infomask bits on the tuple tell readers that it is a lock, so the row stays visible.