Isolation Levels, Locking and MVCC
What happens when transactions run at the same time: MVCC and row versions, the isolation levels and the anomalies they allow, lost updates and how to prevent them, write skew and SERIALIZABLE, row locks with FOR UPDATE, NOWAIT and SKIP LOCKED, deadlocks, and retrying failed transactions.
kvi5hnuCode Sprout team member15 min readOn this page
A database serves many sessions at once: hundreds of web requests, background jobs and reports, all reading and changing the same tables. If each transaction had the database to itself, one after another, there'd be no surprises, but it would be far too slow. So transactions run concurrently, and the database's job is to make that safe.
How safe depends on the isolation level, the "I" in ACID (article 60). This article explains how databases let readers and writers work at the same time, the anomalies each isolation level allows, and the techniques that prevent the classic concurrency bugs: lost updates, write skew and deadlocks.
The concurrency examples need two sessions running at the same time, which a single script can't show, so they're laid out as timelines. Each was run on PostgreSQL 17 with two real sessions, and the results shown are what happened. They use the accounts table from article 60, with Asha's account 1 at 500.00 and Ben's account 2 at 100.00.
MVCC: readers don't wait for writers

PostgreSQL, Oracle, MySQL's InnoDB and, optionally, SQL Server use multiversion concurrency control (MVCC). An UPDATE doesn't overwrite a row in place: it writes a new version of the row, and marks the old version as replaced. Each transaction reads from a snapshot, a view of which transactions had committed at a certain moment, and sees the row versions that were current in that snapshot.
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- MVCC: an UPDATE writes a new version of the row; the old one stays until cleaned up
SELECT ctid AS row_location, account_id, balance FROM accounts ORDER BY account_id;
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE account_id = 1;
SELECT ctid AS row_location, account_id, balance,
xmin = pg_current_xact_id()::xid AS written_by_this_transaction
FROM accounts ORDER BY account_id;
COMMIT;
row_location | account_id | balance
--------------+------------+---------
(0,1) | 1 | 500.00
(0,2) | 2 | 100.00
(2 rows)
row_location | account_id | balance | written_by_this_transaction
--------------+------------+---------+-----------------------------
(0,3) | 1 | 450.00 | t
(0,2) | 2 | 100.00 | f
(2 rows)
ctid is the physical location of a row version, page 0, item 1 and so on. After the update, account 1's current version is at (0,3): a new version was written, and xmin, the ID of the transaction that created it, is the updating transaction. The old version at (0,1) still exists, invisible to new snapshots, until VACUUM, PostgreSQL's background cleanup, reclaims it.
The big benefit: readers never block writers, and writers never block readers. A long report reads a consistent snapshot while updates continue around it. Only two writers changing the same row have to wait for each other.
The costs are the old versions. Tables need regular vacuuming, which autovacuum does automatically. Long-running transactions keep old snapshots alive, so VACUUM can't remove the versions they might need, and tables bloat (article 60).
Isolation levels and anomalies
The SQL standard defines four isolation levels by which anomalies they allow:
| Anomaly | What happens |
|---|---|
| dirty read | reading another transaction's uncommitted changes, which might be rolled back |
| non-repeatable read | reading the same row twice in a transaction and getting different values, because another transaction committed a change in between |
| phantom read | running the same query twice and getting different sets of rows, because another transaction inserted or deleted matching rows |
| serialization anomaly | a result that couldn't have happened if the transactions had run one at a time, in any order |
| Isolation level | Dirty read | Non-repeatable read | Phantom read | Serialization anomaly |
|---|---|---|---|---|
| READ UNCOMMITTED | allowed (not in PostgreSQL) | allowed | allowed | allowed |
| READ COMMITTED | prevented | allowed | allowed | allowed |
| REPEATABLE READ | prevented | prevented | allowed (not in PostgreSQL) | allowed |
| SERIALIZABLE | prevented | prevented | prevented | prevented |
Real databases differ from the standard's table:
- PostgreSQL never allows dirty reads:
READ UNCOMMITTEDbehaves asREAD COMMITTED. ItsREPEATABLE READtakes a snapshot for the whole transaction, which also prevents phantoms. The default is READ COMMITTED. - MySQL InnoDB defaults to REPEATABLE READ. Plain reads use a snapshot, but locking reads and updates see the latest data and take gap (next-key) locks to block phantoms, a common source of MySQL deadlocks.
- SQL Server defaults to
READ COMMITTEDusing locks, where readers wait for writers, unless the database enablesREAD_COMMITTED_SNAPSHOT, which uses row versions instead. It also has a separateSNAPSHOTlevel. - Oracle offers
READ COMMITTED, the default, andSERIALIZABLE, which is really snapshot isolation.
The level is set per transaction, with BEGIN ISOLATION LEVEL REPEATABLE READ or SET TRANSACTION ISOLATION LEVEL ... as the first statement inside the transaction in PostgreSQL, or as a session or server default. In MySQL, SET TRANSACTION comes before START TRANSACTION and applies to the next transaction, and in SQL Server it sets the level for the rest of the session.
READ COMMITTED versus REPEATABLE READ
In READ COMMITTED, each statement sees a fresh snapshot of everything committed before it started. In REPEATABLE READ, the whole transaction sees the snapshot taken at its first statement. Here session B changes Asha's balance while session A reads it twice:
| Step | Session A | Session B |
|---|---|---|
| 1 | BEGIN; (READ COMMITTED) | |
| 2 | SELECT balance ... WHERE account_id = 1; → 500.00 | |
| 3 | UPDATE accounts SET balance = 400 WHERE account_id = 1; (autocommits) | |
| 4 | SELECT balance ... WHERE account_id = 1; → 400.00 | |
| 5 | COMMIT; |
The second read sees B's committed change: a non-repeatable read. Repeating the experiment with BEGIN ISOLATION LEVEL REPEATABLE READ, while B changes the balance to 300:
| Step | Session A | Session B |
|---|---|---|
| 1 | BEGIN ISOLATION LEVEL REPEATABLE READ; | |
| 2 | SELECT balance ...; → 400.00 | |
| 3 | UPDATE accounts SET balance = 300 WHERE account_id = 1; | |
| 4 | SELECT balance ...; → 400.00 | |
| 5 | COMMIT; then SELECT balance ...; → 300.00 |
Inside the transaction, A keeps seeing its snapshot. After it ends, a new statement sees B's change. REPEATABLE READ suits reports that run several queries and need their totals to agree with each other.
Lost updates
The most common concurrency bug in applications is the lost update. Two sessions read a value, compute a new value in the application, and write it back. Each withdraws 50.00 from Asha's 500.00:
| Step | Session A | Session B |
|---|---|---|
| 1 | BEGIN; | |
| 2 | SELECT balance ...; → 500.00 | BEGIN; |
| 3 | SELECT balance ...; → 500.00 | |
| 4 | UPDATE accounts SET balance = 450 ...; (500 − 50, computed in the app) | |
| 5 | UPDATE accounts SET balance = 450 ...; waits for A's row lock | |
| 6 | COMMIT; | the update now runs |
| 7 | COMMIT; → final balance 450.00 |
Two withdrawals of 50.00 should leave 400.00. B's update waited for A's lock, as it should, but then wrote a value computed from a stale read, overwriting A's change. In READ COMMITTED, this goes unnoticed.
Run under REPEATABLE READ in PostgreSQL, step 5 fails once A commits:
ERROR: could not serialize access due to concurrent update
B's snapshot is out of date for that row, so PostgreSQL refuses the update, and B must retry the whole transaction, reading the new balance. MySQL's REPEATABLE READ does not detect this: its updates read the latest committed data, so the lost update happens there too.
There are four standard ways to prevent lost updates:
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- Avoiding lost updates 1: let the database do the arithmetic
UPDATE accounts SET balance = balance - 50 WHERE account_id = 1;
-- Avoiding lost updates 2: optimistic locking with a version number
ALTER TABLE accounts ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
-- A user loaded account 2 at version 1 and saves a change...
UPDATE accounts SET balance = 150.00, version = version + 1
WHERE account_id = 2 AND version = 1
RETURNING account_id, balance, version;
-- ...a second user, who also loaded version 1, tries to save: no row matches
UPDATE accounts SET balance = 90.00, version = version + 1
WHERE account_id = 2 AND version = 1
RETURNING account_id, balance, version;
SELECT account_id, balance, version FROM accounts ORDER BY account_id;
account_id | balance | version
------------+---------+---------
2 | 150.00 | 2
(1 row)
account_id | balance | version
------------+---------+---------
(0 rows)
account_id | balance | version
------------+---------+---------
1 | 450.00 | 1
2 | 150.00 | 2
(2 rows)
- Let the database do the arithmetic.
SET balance = balance - 50reads and writes the row in one statement, under its row lock. If two sessions run it, the second waits, then subtracts from the new value. This is the simplest fix, whenever the change can be expressed in SQL. - Optimistic locking. Add a
versioncolumn. Each update requires the version that was read,WHERE version = 1, and increments it. The first save succeeds and moves the version to 2. The second user, who also read version 1, matches no rows: the application sees zero rows updated and tells the user that someone else changed the record. This suits edits where a person reads a record, thinks, and saves minutes later, with no locks held in between. ORMs support it directly, for example JPA's@Version. - Pessimistic locking. Read the row with
SELECT ... FOR UPDATE, which locks it until the transaction ends. Another session'sFOR UPDATEon the same row waits, then reads the new value. Use it when the read-compute-write must happen in the application inside a short transaction. - A stricter isolation level:
REPEATABLE READorSERIALIZABLEin PostgreSQL turn lost updates into errors, which the application retries.
Write skew and SERIALIZABLE
Some anomalies survive REPEATABLE READ. A hospital rule says at least one doctor must be on call. Kai and Lin are both on call, and each, at the same time, asks to go off duty. The application checks the rule before each change:
| Step | Session A (Kai) | Session B (Lin) |
|---|---|---|
| 1 | BEGIN ISOLATION LEVEL REPEATABLE READ; | |
| 2 | SELECT COUNT(*) FROM on_call WHERE on_duty; → 2 | BEGIN ISOLATION LEVEL REPEATABLE READ; |
| 3 | SELECT COUNT(*) ... WHERE on_duty; → 2 | |
| 4 | UPDATE on_call SET on_duty = false WHERE doctor = 'Kai'; | |
| 5 | COMMIT; | UPDATE on_call SET on_duty = false WHERE doctor = 'Lin'; |
| 6 | COMMIT; → now 0 doctors are on call |
Each transaction saw two doctors, so each thought it was safe to leave. They updated different rows, so neither waited for the other and no conflict was detected. Run one after the other, the second would have seen one doctor and refused. This is write skew, a serialization anomaly.
Under SERIALIZABLE, PostgreSQL tracks which rows each transaction read, as well as which it wrote. When it detects that committing both would produce a result impossible in any serial order, it cancels one:
ERROR: could not serialize access due to read/write dependencies among transactions
DETAIL: Reason code: Canceled on identification as a pivot, during write.
HINT: The transaction might succeed if retried.
In the test run, Lin's update failed. When Lin's transaction is retried, it sees only one doctor on call and refuses. One doctor remains on call.
SERIALIZABLE is the simplest way to be correct: write each transaction as if it ran alone, and the database guarantees the result is equivalent to some serial order. The price is some overhead, and transactions can fail at any statement or at commit, so the application must retry them. Alternatives for specific cases are a constraint that expresses the rule, locking the rows the check depends on with FOR UPDATE, or locking a shared "parent" row that all such transactions update.
Other databases implement SERIALIZABLE differently. MySQL and SQL Server use locks, shared and range locks, so readers can block writers. Oracle's SERIALIZABLE is snapshot isolation, which doesn't prevent write skew, and reports conflicts as ORA-08177. SQL Server's separate SNAPSHOT level behaves like PostgreSQL's REPEATABLE READ, raising error 3960 on update conflicts.
Row locks: FOR UPDATE, NOWAIT and SKIP LOCKED
Writers lock the rows they change until their transaction ends. SELECT ... FOR UPDATE takes the same lock on rows it reads, to change them later in the transaction:
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- Locks held by a transaction: visible in pg_locks until COMMIT or ROLLBACK
BEGIN ISOLATION LEVEL REPEATABLE READ;
SHOW transaction_isolation;
UPDATE accounts SET balance = balance + 10 WHERE account_id = 2;
SELECT * FROM accounts WHERE account_id = 1 FOR UPDATE;
SELECT l.locktype, l.relation::regclass AS object, l.mode, l.granted
FROM pg_locks l
WHERE l.pid = pg_backend_pid() AND l.relation IN ('accounts'::regclass, 'accounts_pkey'::regclass)
ORDER BY l.relation::regclass::text, l.mode;
COMMIT;
transaction_isolation
-----------------------
repeatable read
(1 row)
account_id | owner | balance
------------+-------+---------
1 | Asha | 500.00
(1 row)
locktype | object | mode | granted
----------+---------------+------------------+---------
relation | accounts | RowExclusiveLock | t
relation | accounts | RowShareLock | t
relation | accounts_pkey | RowExclusiveLock | t
relation | accounts_pkey | RowShareLock | t
(4 rows)
pg_locks shows the table-level locks this transaction holds: RowExclusiveLock for the UPDATE and RowShareLock for FOR UPDATE, on the table and its primary key index. These table lock modes don't conflict with each other, so many sessions can update different rows at once. The row locks themselves are stored in the rows, not in pg_locks, so a transaction can lock millions of rows without exhausting memory. They appear in pg_locks only while another session is waiting for them.
Locking options:
| Clause | Behaviour |
|---|---|
FOR UPDATE | lock the rows for changing or deleting; others' FOR UPDATE, updates and deletes wait |
FOR NO KEY UPDATE | a weaker lock for changes that don't touch the key; doesn't block foreign key checks |
FOR SHARE / FOR KEY SHARE | lock against changes while allowing other readers to lock too |
NOWAIT | fail immediately instead of waiting for a locked row |
SKIP LOCKED | skip rows that are locked, instead of waiting |
SKIP LOCKED makes a table work as a job queue with several workers:
-- A job queue: each worker claims jobs no one else has locked
CREATE TABLE jobs (
job_id INTEGER PRIMARY KEY,
task TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued'
);
INSERT INTO jobs (job_id, task) VALUES
(1, 'email receipt 101'), (2, 'email receipt 102'), (3, 'restock alert'), (4, 'nightly report');
BEGIN;
UPDATE jobs SET status = 'running'
WHERE job_id IN (
SELECT job_id FROM jobs
WHERE status = 'queued'
ORDER BY job_id
FOR UPDATE SKIP LOCKED
LIMIT 2
)
RETURNING job_id, task, status;
COMMIT;
SELECT job_id, status FROM jobs ORDER BY job_id;
job_id | task | status
--------+-------------------+---------
1 | email receipt 101 | running
2 | email receipt 102 | running
(2 rows)
job_id | status
--------+---------
1 | running
2 | running
3 | queued
4 | queued
(4 rows)
Each worker claims the first queued jobs that no other worker has locked. While this transaction holds jobs 1 and 2, a second worker running the same statement skips them and claims 3 and 4, without waiting and without both workers taking the same job. MySQL 8.0+ and Oracle support SKIP LOCKED and NOWAIT too, and SQL Server has the READPAST hint.
Deadlocks
A deadlock happens when two transactions each wait for a lock the other holds. Two transfers lock accounts in opposite orders:
| Step | Session A | Session B |
|---|---|---|
| 1 | UPDATE ... WHERE account_id = 1; (locks 1) | |
| 2 | UPDATE ... WHERE account_id = 2; (locks 2) | |
| 3 | UPDATE ... WHERE account_id = 2; waits for B | |
| 4 | UPDATE ... WHERE account_id = 1; waits for A |
Neither can continue. The database detects the cycle, after deadlock_timeout, one second by default in PostgreSQL, and cancels one transaction:
ERROR: deadlock detected
DETAIL: Process 53492 waits for ShareLock on transaction 24929; blocked by process 53493.
Process 53493 waits for ShareLock on transaction 24928; blocked by process 53492.
The other transaction then proceeds. Deadlocks can't be ruled out entirely, but they can be made rare:
- Lock rows in a consistent order, such as by ascending account ID, in every transaction. Two transfers that both lock account 1 before account 2 can't deadlock.
- Keep transactions short, so locks are held briefly.
- Lock everything you'll need up front, for example with one
SELECT ... FOR UPDATE ... ORDER BY account_id.
Retrying transactions
Serialization failures (SQLSTATE 40001) and deadlocks (40P01 in PostgreSQL) mean "this transaction conflicted with another; try again". They're a normal part of concurrent systems, not bugs. Applications should:
- roll back and re-run the whole transaction, including its reads, not just the failed statement
- retry a few times, with a short random delay
- keep side effects, such as sending email, outside the transaction, so they don't happen twice
Many frameworks and drivers provide retry helpers.
Other tools worth knowing: lock_timeout makes a statement fail instead of waiting longer than a limit for a lock (article 53), and PostgreSQL's advisory locks (pg_advisory_lock) let applications lock arbitrary numbers, for example to ensure only one instance of a scheduled job runs at a time.
Locking a whole table
Row locks cover most needs, but sometimes a job needs a whole table to stay unchanged, such as a batch that recalculates every balance. LOCK TABLE accounts IN SHARE MODE lets others read but blocks all changes until the transaction ends, and IN EXCLUSIVE MODE also blocks other locking reads. In PostgreSQL, ACCESS EXCLUSIVE, the default mode, blocks even plain reads, as ALTER TABLE does. Oracle has the same LOCK TABLE ... IN ... MODE syntax, MySQL has LOCK TABLES, and SQL Server uses table hints such as WITH (TABLOCKX).
Table locks hurt concurrency, so use them only for short operations, with NOWAIT or a lock_timeout so a blocked job fails fast instead of queueing every other session behind it.
What's current
- SQL Server 2025 added optimized locking, which holds row locks only briefly and reduces lock memory and blocking, building on accelerated database recovery.
- PostgreSQL 17 sped up vacuuming and reduced its memory use, which helps systems with heavy update traffic and many row versions.
- MySQL 8.0 added
NOWAITandSKIP LOCKED. PostgreSQL addedSKIP LOCKEDin 9.5 and has hadNOWAITfar longer.
Common questions
Which isolation level should I use?
The default, READ COMMITTED, with atomic updates or row locks where needed, suits most applications. Use REPEATABLE READ for consistent multi-query reports, and SERIALIZABLE when correctness depends on reads, with retries.
Do readers block writers? Not with MVCC, used by PostgreSQL, Oracle and MySQL InnoDB. In SQL Server's default locking mode, they can, unless snapshot-based isolation is enabled.
What's the difference between optimistic and pessimistic locking? Pessimistic locking locks rows when they're read, so others wait. Optimistic locking takes no lock and checks a version number at write time, failing if someone else changed the row.
Why did my transaction fail with "could not serialize access"?
It conflicted with a concurrent transaction under REPEATABLE READ or SERIALIZABLE. Retry the whole transaction.
How do I avoid deadlocks? Access and lock rows in the same order everywhere, keep transactions short, and retry when one occurs.
Summary
- MVCC keeps row versions so readers and writers don't block each other.
VACUUMremoves old versions. - Isolation levels trade anomalies for concurrency. PostgreSQL defaults to
READ COMMITTED, MySQL toREPEATABLE READ. READ COMMITTEDgives each statement a fresh snapshot.REPEATABLE READkeeps one snapshot per transaction.- Prevent lost updates with atomic
UPDATEs, optimistic version checks,SELECT ... FOR UPDATE, or stricter isolation. - Write skew needs
SERIALIZABLE, a constraint, or explicit locks. FOR UPDATE,NOWAITandSKIP LOCKEDcontrol row locking.SKIP LOCKEDmakes job queues easy.- Deadlocks are detected and one transaction is cancelled. Lock in a consistent order.
- Retry transactions that fail with serialization errors or deadlocks.
Practice questions
Two sessions each run UPDATE products SET stock = stock - 1 WHERE product_id = 3 at the same time, starting from stock 40. What's the final stock in READ COMMITTED?
Answer
- The second update waits for the first's row lock, then re-reads the row and subtracts from 39. Atomic updates don't lose changes.
An application reads stock (40), subtracts 1 in its own code, and writes SET stock = 39. Two requests do this at once. What can happen, and how would you fix it?
Answer
A lost update: both read 40, both write 39, so one sale is lost. Fix it with an atomic SET stock = stock - 1, a SELECT ... FOR UPDATE before computing, or an optimistic version check, or run under REPEATABLE READ in PostgreSQL and retry on serialization errors.
Write a query that claims the oldest queued job, skipping jobs that other workers have locked.
Answer
UPDATE jobs SET status = 'running'
WHERE job_id = (
SELECT job_id FROM jobs
WHERE status = 'queued'
ORDER BY job_id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING job_id, task;
Two transfer transactions keep deadlocking. One moves money from account 1 to 2, the other from 2 to 1. How can the code avoid this?
Answer
Lock the two accounts in the same order in every transfer, for example the lower account ID first, either by updating them in that order or with SELECT ... FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id FOR UPDATE at the start. Also retry when a deadlock still occurs.
Previous: Transactions: COMMIT, ROLLBACK, Savepoints and ACID

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.