AI Hints
Home›PostgreSQL Tutorial›Transactions and MVCC
PostgreSQL · Lesson 66 of 120

MVCC

Many versions of a row.

⏱ 2 min read▶ Video at 59:14🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Alice is changing a price, but hasn't committed. At that moment, Bob reads the same book. Postgres doesn't make Bob wait. Bob sees the old version, because Postgres keeps several versions of a row. That's MVCC.

  • Alice writes
  • Bob reads
  • No waiting

Two sessions, two versions

Alice and Bob are two connections. Alice updates the price, without committing. Bob reads it, and sees the old price. After Alice commits, Bob sees the new one. Run it. Readers never wait for writers.

mvcc.pypython
import psycopg

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
alice = psycopg.connect(URL)   # first session
bob = psycopg.connect(URL)     # second session

sql = "SELECT price FROM books WHERE book_id = 1"
alice.execute("UPDATE books SET price = 19.99 WHERE book_id = 1")
print("Bob before commit:", bob.execute(sql).fetchone()[0])
alice.commit()
print("Bob after commit: ", bob.execute(sql).fetchone()[0])
Output
Bob before commit: 14.99
Bob after commit:  19.99

MVCC in short

Every update writes a new row version, and marks the old one as dead. Each transaction sees a snapshot. Readers don't block writers, and writers don't block readers. Vacuum cleans up dead versions later.

keyvalue
UPDATEnew version
Snapshotwhat you see
No blockingreads vs writes
VACUUMremoves dead rows

Summary

MVCC keeps row versions, so readers and writers don't block each other. Next, isolation levels.

Key takeaways
  • Versions
  • Snapshots
  • VACUUM
Next up: Isolation Levels — what each transaction sees