AI Hints
Home›PostgreSQL Tutorial›Isolation, Locks and Job Queues
PostgreSQL · Lesson 67 of 120

Isolation Levels

What each transaction sees.

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

Bob is running a long report. Halfway through, Alice changes a price and commits. Should Bob's report see the new price or not? The isolation level decides.

  • Bob's long report
  • Alice commits
  • What does Bob see?

Read committed vs repeatable read

Bob starts a repeatable read transaction, and reads the price. Alice changes it and commits. Bob reads again, and still sees the old price, because his snapshot is frozen. Run it. A stable view for the whole report.

isolation.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"
bob.execute("BEGIN ISOLATION LEVEL REPEATABLE READ")
print("Bob reads: ", bob.execute(sql).fetchone()[0])

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

The levels

Read committed is the default, and each statement sees the latest committed data. Repeatable read freezes one snapshot for the whole transaction. Serializable also stops subtle conflicts, and may ask you to retry.

LevelSees
READ COMMITTEDlatest, per statement (default)
REPEATABLE READone snapshot
SERIALIZABLEas if one at a time

Summary

Isolation levels decide what a transaction sees, from latest data to one frozen snapshot. Next, locks and deadlocks.

Key takeaways
  • READ COMMITTED
  • REPEATABLE READ
  • SERIALIZABLE
Next up: Locks and Deadlocks — waiting your turn