Predict the output · Python

Read Committed vs Repeatable Read

Medium Predict the output

This toy MVCC store keeps committed versions with their commit time. What does it print? See Isolation Levels in Postgres vs MySQL.

What does this print?

committed = [(1, 1000)]             # (commit_time, balance)

def read(as_of):
    return max(v for v in committed if v[0] <= as_of)[1]

snapshot = 1                        # the report's first statement runs at t=1
first = read(snapshot)
committed.append((2, 1250))         # a deposit commits at t=2
read_committed = read(2)            # second statement under READ COMMITTED
repeatable_read = read(snapshot)    # second statement under REPEATABLE READ
print(first, read_committed, repeatable_read)
  1. 1000 1000 1000
  2. 1000 1250 1000
  3. 1000 1250 1250
  4. 1250 1250 1250

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

1000 1250 1000

Under Read Committed (Postgres's default) every statement sees data committed before it started, so the second read sees the deposit. Under Repeatable Read (MySQL InnoDB's default) the whole transaction reads from the snapshot taken at its first read. Multi-statement reports therefore need Repeatable Read to add up. See Isolation Levels.