Introduction
MVCC helps PostgreSQL handle many users working with the database at the same time without conflicts.
Jump into concepts and practice - no test required
MVCC helps PostgreSQL handle many users working with the database at the same time without conflicts.
-- MVCC is a concept, not a command. It works automatically in PostgreSQL.BEGIN; SELECT * FROM products WHERE id = 1; -- Transaction sees data as it was at BEGIN UPDATE products SET price = 20 WHERE id = 1; COMMIT;
BEGIN; SELECT * FROM products WHERE id = 1; -- Another transaction updates the same row here COMMIT;
Transaction 1 starts and reads price 10. Transaction 2 updates price to 15 and commits. Transaction 1 still sees price 10 until it ends.
-- Setup table and data CREATE TABLE products (id SERIAL PRIMARY KEY, name TEXT, price INT); INSERT INTO products (name, price) VALUES ('Apple', 10); -- Transaction 1 BEGIN; SELECT price FROM products WHERE name = 'Apple'; -- Returns 10 -- Transaction 2 (in another session) BEGIN; UPDATE products SET price = 15 WHERE name = 'Apple'; COMMIT; -- Back to Transaction 1 SELECT price FROM products WHERE name = 'Apple'; COMMIT;
MVCC avoids locking delays by letting readers see old data versions.
Writers create new row versions; old versions are cleaned later.
This helps keep the database fast and consistent for many users.
MVCC lets many users work with data at the same time without waiting.
Each transaction sees a snapshot of data as it was when it started.
PostgreSQL keeps old row versions to support this snapshot view.
BEGIN; to start a transaction.BEGIN;
SELECT * FROM products WHERE id = 1;
UPDATE products SET price = 20 WHERE id = 1;
COMMIT;BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SELECT balance FROM accounts WHERE id = 1;
ROLLBACK;