Tell us about MVCC (Multi-Version Concurrency Control) in PostgreSQL.
sobes.tech AI
Answer from AI
MVCC (Multi-Version Concurrency Control) in PostgreSQL is a concurrency control mechanism that allows multiple transactions to read and write data simultaneously without read locks.
The main idea of MVCC is to store multiple versions of the same row in a table. Each version has transaction markers (xmin, xmax) that determine in which transactions this version is visible.
When a transaction reads data, it only sees the versions of rows that were current at the start of its operation, ignoring changes made by parallel uncommitted transactions. This ensures read isolation and prevents locking.
When updating a row, PostgreSQL does not overwrite it directly but creates a new version with a new xmin, and the old version gets an xmax indicating it is no longer current for new transactions.
Example:
BEGIN;
SELECT * FROM users WHERE id = 1; -- sees the version of the row valid at the start of the transaction
UPDATE users SET name = 'NewName' WHERE id = 1; -- creates a new version of the row
COMMIT;
Thus, MVCC improves performance and concurrency by reducing locks and conflicts between transactions.