Video in progress

How does MVCC work in PostgreSQL, and what does an UPDATE actually do on disk?

Each row version carries the IDs of the transaction that created it (xmin) and the one that deleted it (xmax). An UPDATE doesn't modify the old row in place: it sets xmax on it and writes a new version somewhere else. Each transaction decides which version it sees based on its snapshot.

📖 Answer

That is why in PostgreSQL readers don't block writers and vice versa: a reading transaction keeps seeing the old version, and the writing one creates a new one.

You can look inside:

SELECT xmin, xmax, ctid, * FROM account WHERE id = 1;
--  xmin | xmax | ctid  | id | balance
--  1001 |    0 | (0,1) |  1 |     100

UPDATE account SET balance = 90 WHERE id = 1;

SELECT xmin, xmax, ctid, * FROM account WHERE id = 1;
--  1002 |    0 | (0,2) |  1 |      90   -- new location, new xmin

The old (0,1) version is still on the page, and its xmax is 1002. A transaction whose snapshot was taken before 1002 still sees it.

The price of this design:

  • bloat: every UPDATE and DELETE leaves a dead row, and VACUUM cleans them up;
  • index updates: the new version is at a new ctid, so (unless it's a HOT update) a new entry is added to all the indexes, even the indexes on columns that didn't change;
  • write amplification: changing one column rewrites the whole row.

Oracle and MySQL InnoDB take a different route: they update the row in place and write the old version to an undo log. PostgreSQL has no undo log, so ROLLBACK is instant, but the cleanup work falls on VACUUM.