SQL course · Module 10: Concurrency · Lesson 34 of 40
Quick answer: Transaction isolation levels decide what a transaction can see of other transactions running at the same time. The standard has four: Read Uncommitted, Read Committed, Repeatable Read and Serializable. PostgreSQL uses Read Committed by default and never shows uncommitted data. Higher levels can fail with a serialization error, and then you retry the whole transaction. When two sessions wait for each other’s locks, PostgreSQL reports a deadlock and cancels one.
In this lesson you will learn:
- the four read phenomena, and which isolation level allows which one in PostgreSQL
- how to choose an isolation level with
BEGIN ISOLATION LEVELandSET TRANSACTION - what Read Committed, Repeatable Read and Serializable look like with two real sessions
- row locks:
SELECT ... FOR UPDATE,FOR SHARE,NOWAITandSKIP LOCKED - how a deadlock happens, how to avoid it, and what
lock_timeoutdoes
Before you start: Lesson 19, SQL Transactions: BEGIN, COMMIT, ROLLBACK and SAVEPOINT and Lesson 33, SQL Query Optimization: A Practical Checklist.
We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3 and checked the current PostgreSQL 18 manual; it works the same on newer versions. For the demos we drove two real psql sessions, A and B, with a script, one step every 2 seconds. You can type the same steps into two terminal windows. Run \i shop.sql before each demo.
Table of Contents
Why transaction isolation levels exist: the four read phenomena
What if another session commits a change while your transaction is still running? The manual describes four problems, called phenomena (PostgreSQL docs: Transaction Isolation):
- Dirty read: you read data that another transaction wrote but has not committed yet.
- Non-repeatable read: you read a row twice and get different values, because another transaction changed it and committed in between.
- Phantom read: you run the same query twice and get a different set of rows, because another transaction added or removed matching rows.
- Serialization anomaly: a group of transactions gives a result that no one-at-a-time order of those transactions could give.
This table from the manual shows which level allows which problem. “Allowed, but not in PG” means the standard allows it, but PostgreSQL does not:
| isolation level | dirty read | non-repeatable read | phantom read | serialization anomaly |
|---|---|---|---|---|
| Read uncommitted | Allowed, but not in PG | Possible | Possible | Possible |
| Read committed | Not possible | Possible | Possible | Possible |
| Repeatable read | Not possible | Not possible | Allowed, but not in PG | Possible |
| Serializable | Not possible | Not possible | Not possible | Not possible |
The manual explains: “internally only three distinct isolation levels are implemented, i.e., PostgreSQL’s Read Uncommitted mode behaves like Read Committed.”
How to choose an isolation level
Check the level of your session first:
SHOW transaction_isolation;
transaction_isolation
-----------------------
read committed
(1 row)
To use another level for one transaction, put it in BEGIN, or run SET TRANSACTION right after BEGIN:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SHOW transaction_isolation;
COMMIT;
BEGIN
transaction_isolation
-----------------------
repeatable read
(1 row)
COMMIT
The level “cannot be changed after the first query or data-modification statement” (PostgreSQL docs: SET TRANSACTION). If you are too late, you get an error, and the transaction is aborted:
ERROR: SET TRANSACTION ISOLATION LEVEL must be called before any query
Read Committed: every statement sees fresh data
In Read Committed, each statement sees the rows committed before that statement began. Session A opens a transaction and reads a price and a count. Session B (in autocommit mode) changes the price and adds a pending order. Then A reads again:
--- Session A
BEGIN;
BEGIN
SHOW transaction_isolation;
transaction_isolation
-----------------------
read committed
(1 row)
SELECT price FROM products WHERE id = 2;
price
-------
89.00
(1 row)
SELECT count(*) FROM orders WHERE status = 'pending';
count
-------
1
(1 row)
--- Session B
UPDATE products SET price = 95.00 WHERE id = 2;
UPDATE 1
INSERT INTO orders (customer_id, order_date, status) VALUES (10, '2026-11-08', 'pending');
INSERT 0 1
--- Session A
SELECT price FROM products WHERE id = 2;
price
-------
95.00
(1 row)
SELECT count(*) FROM orders WHERE status = 'pending';
count
-------
2
(1 row)
Inside one transaction, A saw the price change from 89.00 to 95.00 (a non-repeatable read) and the count change from 1 to 2 (a phantom read). For most apps this is fine.
Read Uncommitted shows no dirty data in PostgreSQL
Now session B changes the price to 1.00 but does not commit. Session A asks for Read Uncommitted and reads the row:
--- Session A
BEGIN ISOLATION LEVEL READ UNCOMMITTED;
BEGIN
SELECT price FROM products WHERE id = 2;
price
-------
89.00
(1 row)
A saw 89.00, not B’s uncommitted 1.00. PostgreSQL accepts the name (SHOW even says read uncommitted), but the behaviour is Read Committed.
Repeatable Read: one snapshot for the whole transaction
In Repeatable Read, a transaction “sees a snapshot as of the start of the first non-transaction-control statement”. We ran the same steps, but A began with BEGIN ISOLATION LEVEL REPEATABLE READ. After B’s changes, A read again and tried to change the row:
--- Session A
SELECT price FROM products WHERE id = 2;
price
-------
89.00
(1 row)
SELECT count(*) FROM orders WHERE status = 'pending';
count
-------
1
(1 row)
UPDATE products SET price = price + 1 WHERE id = 2;
ERROR: could not serialize access due to concurrent update
ROLLBACK;
ROLLBACK
SELECT price FROM products WHERE id = 2;
price
-------
95.00
(1 row)
A still saw 89.00 and a count of 1. But A could not update a row that B had changed after A’s snapshot, because A would have changed a price it never saw. The manual’s advice: “abort the current transaction and retry the whole transaction from the beginning.” After the ROLLBACK, A sees 95.00.
Serializable: PostgreSQL stops the anomaly
Say our shop has a rule: a customer may have only one pending order. The app counts with a SELECT, and inserts if the count is 0. Both sessions do this for Omar (customer 10) at the same time, in Read Committed. Both counted 0. The end of the run:
--- Session A
INSERT INTO orders (customer_id, order_date, status) VALUES (10, '2026-11-08', 'pending');
INSERT 0 1
--- Session B
INSERT INTO orders (customer_id, order_date, status) VALUES (10, '2026-11-08', 'pending');
INSERT 0 1
--- Session A
COMMIT;
COMMIT
--- Session B
COMMIT;
COMMIT
SELECT count(*) FROM orders WHERE customer_id = 10 AND status = 'pending';
count
-------
2
(1 row)
Omar now has two pending orders: a serialization anomaly. Repeatable Read gave the same result. With BEGIN ISOLATION LEVEL SERIALIZABLE in both sessions:
--- Session A
COMMIT;
COMMIT
--- Session B
COMMIT;
ERROR: could not serialize access due to read/write dependencies among transactions
DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt.
HINT: The transaction might succeed if retried.
B failed at COMMIT, so only one order was saved. \echo SQLSTATE :LAST_ERROR_SQLSTATE printed SQLSTATE 40001. B then retried the whole transaction; its count was now 1, so it did not insert.
This is the retry rule: on SQLSTATE 40001, “retry the complete transaction, including all logic that decides which SQL to issue” (PostgreSQL docs: Serialization Failure Handling). PostgreSQL does not retry for you; your app must. For this exact rule, a partial unique index (Lesson 31) on orders (customer_id) WHERE status = 'pending' is simpler: in our test it rejected the second pending order, and with ON CONFLICT (Lesson 18) the second insert added 0 rows.
Row locks: FOR UPDATE, FOR SHARE, NOWAIT and SKIP LOCKED
UPDATE and DELETE lock the rows they change until the transaction ends. You can also lock rows while you read them (PostgreSQL docs: Explicit Locking):
FOR UPDATE: others cannot lock, change or delete the rows until your transaction ends.FOR SHARE: others can also takeFOR SHARE, but cannotUPDATEorDELETEthe rows.NOWAITreports an error instead of waiting for a locked row.SKIP LOCKEDskips locked rows. This “provides an inconsistent view of the data”, so use it only for queue-like tables (PostgreSQL docs: SELECT).
A common use is a job queue. Two workers each take the next shipped order:
--- Session A
BEGIN;
BEGIN
SELECT id, status FROM orders WHERE status = 'shipped' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
id | status
----+---------
19 | shipped
(1 row)
--- Session B
BEGIN;
BEGIN
SELECT id, status FROM orders WHERE id = 19 FOR UPDATE NOWAIT;
ERROR: could not obtain lock on row in relation "orders"
ROLLBACK;
ROLLBACK
BEGIN;
BEGIN
SELECT id, status FROM orders WHERE status = 'shipped' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
id | status
----+---------
20 | shipped
(1 row)
A had locked order 19, so NOWAIT failed at once (SQLSTATE 55P03), and SKIP LOCKED gave B the next free order, 20.
lock_timeout: do not wait forever
lock_timeout limits how long a statement waits for a lock; the default, 0, means no limit (PostgreSQL docs: Client Connection Defaults). Here A holds a FOR SHARE lock on product 3. B can take the same shared lock, but its UPDATE must wait, and gives up after 3 seconds:
--- Session B
BEGIN;
BEGIN
SELECT name, price FROM products WHERE id = 3 FOR SHARE;
name | price
-----------+-------
USB-C Hub | 39.50
(1 row)
SET lock_timeout = '3s';
SET
UPDATE products SET price = 41.00 WHERE id = 3;
ERROR: canceling statement due to lock timeout
CONTEXT: while updating tuple (0,3) in relation "products"
Do not set it in postgresql.conf, “because it would affect all sessions”. SET LOCAL lock_timeout = '3s' inside a transaction lasts only until it ends.
Deadlocks: a real one, and the fix
A deadlock happens when A waits for a row that B has locked, while B waits for a row that A has locked. Here A updates product 1 then 2, and B updates product 2 then 1. The end of the run:
--- Session A
UPDATE products SET price = price + 1 WHERE id = 2;
--- Session B
UPDATE products SET price = price + 1 WHERE id = 1;
ERROR: deadlock detected
DETAIL: Process 17998 waits for ShareLock on transaction 4900; blocked by process 17997.
Process 17997 waits for ShareLock on transaction 4911; blocked by process 17998.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,1) in relation "products"
UPDATE 1
SQLSTATE 40P01
After deadlock_timeout (1 second by default), PostgreSQL found the cycle and aborted B’s transaction. The UPDATE 1 under the error is A’s waiting update, which then finished. The process and transaction numbers in DETAIL change on every run, so yours will differ; the SQLSTATE line is from our \echo. Which transaction is aborted “is difficult to predict and should not be relied upon”.

The fix is to take locks in the same order everywhere, “the best defense against deadlocks”. Here both sessions first lock both rows in id order. B’s SELECT ... FOR UPDATE waits until A commits, then gets its turn:
--- Session B
BEGIN;
BEGIN
SELECT id FROM products WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
--- Session A
UPDATE products SET price = price + 1 WHERE id = 2;
UPDATE 1
UPDATE products SET price = price + 1 WHERE id = 1;
UPDATE 1
COMMIT;
COMMIT
id
----
1
2
(2 rows)
--- Session B
UPDATE products SET price = price + 1 WHERE id = 1;
UPDATE 1
UPDATE products SET price = price + 1 WHERE id = 2;
UPDATE 1
COMMIT;
COMMIT
SELECT id, price FROM products WHERE id IN (1, 2) ORDER BY id;
id | price
----+-------
1 | 26.99
2 | 91.00
(2 rows)
No deadlock: each price went up by 2. (B’s waiting result appears in the log right after A’s COMMIT.) Also keep transactions short; holding them open “while waiting for user input” is “a bad idea”. If a deadlock still happens, retry; its SQLSTATE is 40P01.
Try it yourself
Exercise 1: Change the level for one transaction
Show your session’s isolation level. Then start a transaction, set it to Repeatable Read with SET TRANSACTION, check it with SHOW, count the orders and commit.
Exercise 2: Does FOR UPDATE block readers?
In session A, run BEGIN and lock order 22 with FOR UPDATE. In session B, read order 22 with a plain SELECT, then try FOR UPDATE NOWAIT. Commit A at the end.
Exercise 3: A lock timeout for one transaction
In one transaction, set lock_timeout to 2 seconds with SET LOCAL, lock order 22 with FOR UPDATE and show the setting. Commit, and show the setting again.
Solutions
Solution 1
SHOW transaction_isolation;
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SHOW transaction_isolation;
SELECT count(*) FROM orders;
COMMIT;
transaction_isolation
-----------------------
read committed
(1 row)
BEGIN
SET
transaction_isolation
-----------------------
repeatable read
(1 row)
count
-------
22
(1 row)
COMMIT
SET TRANSACTION must come before the SELECT; it changes only this transaction.
Solution 2
--- Session A
BEGIN;
BEGIN
SELECT id, status FROM orders WHERE id = 22 FOR UPDATE;
id | status
----+---------
22 | pending
(1 row)
--- Session B
SELECT id, status FROM orders WHERE id = 22;
id | status
----+---------
22 | pending
(1 row)
SELECT id, status FROM orders WHERE id = 22 FOR UPDATE NOWAIT;
ERROR: could not obtain lock on row in relation "orders"
A plain SELECT does not wait for row locks; only writers and other locking reads do.
Solution 3
BEGIN;
SET LOCAL lock_timeout = '2s';
SELECT id, status FROM orders WHERE id = 22 FOR UPDATE;
SHOW lock_timeout;
COMMIT;
SHOW lock_timeout;
BEGIN
SET
id | status
----+---------
22 | pending
(1 row)
lock_timeout
--------------
2s
(1 row)
COMMIT
lock_timeout
--------------
0
(1 row)
SET LOCAL lasted only until COMMIT; afterwards the default 0 (no limit) is back.
Common mistakes
- Setting the level too late. After the first query you get
ERROR: SET TRANSACTION ISOLATION LEVEL must be called before any query. Put the level inBEGIN. - Locking an aggregate.
SELECT count(*) FROM orders WHERE status = 'shipped' FOR UPDATE;givesERROR: FOR UPDATE is not allowed with aggregate functions. Lock the rows themselves. - Retrying only the failed statement. After error 40001 or 40P01, roll back and run the whole transaction again, including the reads that decided what to write.
- SET LOCAL outside a transaction. You get
WARNING: SET LOCAL can only be used in transaction blocks, and nothing changes.
Frequently asked questions
What is the default transaction isolation level in PostgreSQL?
Read Committed (check with SHOW transaction_isolation;). MySQL differs: “The default isolation level for InnoDB is REPEATABLE READ” (MySQL 8.4: Transaction Isolation Levels).
How do I fix “deadlock detected” in PostgreSQL?
Make every part of your app lock rows in the same order, for example by id, and keep transactions short. Catch SQLSTATE 40P01 and retry the whole transaction.
What is the difference between Repeatable Read and Serializable?
Both read from one snapshot taken at the first statement. Serializable also watches how concurrent transactions read and write, and cancels one when the result could not come from running them one at a time. In our test, Repeatable Read let both pending orders through; Serializable stopped the second with error 40001.
Summary
- Isolation levels decide what a transaction sees of concurrent work; PostgreSQL runs three of the four standard levels and never shows dirty reads.
- Read Committed (the default) gives each statement a fresh view; Repeatable Read keeps one snapshot for the whole transaction.
- Repeatable Read and Serializable can fail with SQLSTATE 40001; retry the complete transaction.
FOR UPDATEandFOR SHARElock rows;NOWAITerrors at once,SKIP LOCKEDskips locked rows, andlock_timeoutlimits the wait.- Deadlocks come from opposite lock order; lock in one consistent order and retry on
40P01.
Next lesson
Next: Lesson 35, PostgreSQL JSONB and Arrays for Semi-Structured Data.
Sources
- PostgreSQL documentation: Transaction Isolation
- PostgreSQL documentation: Serialization Failure Handling
- PostgreSQL documentation: Explicit Locking (row-level locks, deadlocks)
- PostgreSQL documentation: SELECT (the locking clause)
- PostgreSQL documentation: SET TRANSACTION
- PostgreSQL documentation: Client Connection Defaults (lock_timeout)
- PostgreSQL documentation: Lock Management (deadlock_timeout)
- PostgreSQL documentation: Error Codes
- PostgreSQL documentation: psql (LAST_ERROR_SQLSTATE)
- MySQL 8.4 Reference Manual: Transaction Isolation Levels





