Locks and Deadlocks
A lock in SQL is a mark a transaction places on a row or table so that conflicting changes by other transactions have to wait. It is used to keep concurrent writers from overwriting each other's work. PostgreSQL takes most locks automatically: every UPDATE locks the rows it changes until the transaction ends. In this lesson, we will see which locks common statements take, lock rows on purpose with SELECT ... FOR UPDATE, understand deadlocks and how to avoid them, and fix the lost update from Isolation Levels in two ways.
In One Minute
UPDATEandDELETElock the rows they change untilCOMMITorROLLBACK; other writers of those rows wait.- Plain
SELECTtakes no row locks: reading a row never blocks changing it, and changing a row never blocks reading it. (ASELECTdoes make schema changes likeALTER TABLEwait.) SELECT ... FOR UPDATElocks rows you plan to change, so nobody changes them first.- A deadlock is two transactions each waiting for a lock the other holds; PostgreSQL cancels one.
- Optimistic locking uses a
versioncolumn instead: update only if nobody changed the row since you read it.
Locks That Statements Take
PostgreSQL records the locks each session holds in the pg_locks view. A transaction that updates a course holds a lock on the table that lets others read but blocks conflicting schema changes:
BEGIN;
UPDATE courses SET fee_usd = 410 WHERE course_id = 4;
SELECT l.mode, c.relname AS table_name
FROM pg_locks AS l
JOIN pg_class AS c ON c.oid = l.relation
WHERE l.pid = pg_backend_pid() AND c.relname = 'courses';
ROLLBACK;BEGIN
UPDATE 1
mode | table_name
------------------+------------
RowExclusiveLock | courses
(1 row)
ROLLBACKExplanation: RowExclusiveLock is the table-level lock every INSERT, UPDATE and DELETE takes; it doesn't block other writers on other rows. The changed row itself is locked separately (row locks are stored in the row, not listed here), so another transaction trying to update course 4 would wait until this one ends.
| Statement | Table lock | Row lock | Blocks |
|---|---|---|---|
SELECT | AccessShare | none | Only DROP and similar schema changes |
SELECT ... FOR UPDATE | RowShare | the selected rows | Other updates and FOR UPDATE of those rows |
INSERT, UPDATE, DELETE | RowExclusive | the changed rows | Other updates of those rows |
ALTER TABLE, DROP TABLE, LOCK TABLE | AccessExclusive | Everything on the table, even reads |
SELECT ... FOR UPDATE
SELECT ... FOR UPDATE locks the selected rows as if they were about to be updated, so no other transaction can change them until you finish:
BEGIN;
SELECT title, fee_usd FROM courses WHERE course_id = 4 FOR UPDATE;
SELECT l.mode, c.relname AS locked_object
FROM pg_locks AS l
JOIN pg_class AS c ON c.oid = l.relation
WHERE l.pid = pg_backend_pid() AND c.relname IN ('courses', 'courses_pkey')
ORDER BY c.relname;
COMMIT;BEGIN
title | fee_usd
------------+---------
SQL Basics | 400.00
(1 row)
mode | locked_object
--------------+---------------
RowShareLock | courses
RowShareLock | courses_pkey
(2 rows)
COMMITExplanation: The session now holds RowShareLock on the table and its key index, and a row lock on course 4. Another session's UPDATE or SELECT ... FOR UPDATE of that course would wait until this transaction commits. FOR UPDATE NOWAIT fails immediately instead of waiting, and FOR UPDATE SKIP LOCKED skips rows other sessions have locked, which is how job queues hand out work.
Fixing a Lost Update
In Isolation Levels, two sessions each read Navika's 45 minutes and wrote back their own total, losing one change. Try it has one session, so we play both sessions in order in one window:
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
-- Session A reads 45. Session B reads 45.
SELECT minutes FROM study_totals WHERE student_id = 103;
SELECT minutes FROM study_totals WHERE student_id = 103;
-- A writes 45 + 30. B writes 45 + 60, from its stale read.
UPDATE study_totals SET minutes = 45 + 30 WHERE student_id = 103;
UPDATE study_totals SET minutes = 45 + 60 WHERE student_id = 103;
SELECT minutes AS final FROM study_totals;CREATE TABLE
INSERT 0 1
minutes
---------
45
(1 row)
minutes
---------
45
(1 row)
UPDATE 1
UPDATE 1
final
-------
105
(1 row)Explanation: The final value is 105, but 45 + 30 + 60 is 135. Session A's 30 minutes were overwritten because B computed its new value from an old read. Two fixes:
Fix 1: an atomic update. Let the database read and write in one statement, so each update starts from the current value:
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
UPDATE study_totals SET minutes = minutes + 30 WHERE student_id = 103;
UPDATE study_totals SET minutes = minutes + 60 WHERE student_id = 103;
SELECT minutes AS final FROM study_totals;CREATE TABLE
INSERT 0 1
UPDATE 1
UPDATE 1
final
-------
135
(1 row)Explanation: minutes = minutes + 30 reads the value inside the update, after waiting for any other writer, so concurrent sessions can't lose each other's changes: 135.
Fix 2: lock before reading. When the new value needs logic in the program, read with SELECT ... FOR UPDATE inside the transaction. The second session's FOR UPDATE waits until the first commits, then reads 75, not 45.
Deadlocks
A deadlock happens when two transactions each hold a lock the other needs. Session A updates Java Basics, then tries to update Java OOP; session B updated Java OOP first, and now tries Java Basics. Each waits for the other, forever. PostgreSQL checks for this after deadlock_timeout (1 second by default), cancels one transaction with ERROR: deadlock detected, and lets the other continue.
SHOW deadlock_timeout; deadlock_timeout
------------------
1s
(1 row)Optimistic Locking
Optimistic locking doesn't lock at read time; it checks at write time that the row hasn't changed. Add a version column, and make every update require the version you read:
ALTER TABLE courses ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
-- Two people both read SQL Basics at version 1.
UPDATE courses SET fee_usd = 420, version = version + 1
WHERE course_id = 4 AND version = 1
RETURNING course_id, fee_usd, version;
UPDATE courses SET fee_usd = 430, version = version + 1
WHERE course_id = 4 AND version = 1
RETURNING course_id, fee_usd, version;ALTER TABLE
course_id | fee_usd | version
-----------+---------+---------
4 | 420.00 | 2
(1 row)
course_id | fee_usd | version
-----------+---------+---------
(0 rows)Explanation: The first update matches version 1 and bumps it to 2. The second still says version = 1, matches no row, and returns nothing. The program sees "0 rows updated", tells the second person the course changed, and lets them reload. It suits web forms, where a user may take minutes between reading and saving, and holding a lock that long would block everyone.
Common Mistakes
Reading a value, computing in the program, and writing it back. That's the lost update. Use an atomic update or FOR UPDATE.
Holding locks while waiting for a person. Keep transactions short; use optimistic locking for forms.
Locking rows in different orders. Inconsistent order causes deadlocks.
Treating a deadlock error as fatal. Retry the canceled transaction.
Interview Corner
What does SELECT ... FOR UPDATE do?
It locks the selected rows until the transaction ends, so other transactions can't update, delete or lock them for update in the meantime.
What is a deadlock, and how is it handled?
Two transactions each waiting for a lock the other holds. The database detects the cycle and aborts one of them; the application should retry it. Consistent lock ordering prevents most deadlocks.
What's the difference between pessimistic and optimistic locking?
Pessimistic locking locks rows when reading (FOR UPDATE) so others wait. Optimistic locking doesn't lock; it checks a version column at update time and fails if the row changed.
Practice
Challenge (module checkpoint): Reproduce the lost update by playing two sessions in one window: start Navika's total at 45, have both "sessions" read it, then write 45 + 30 and 45 + 60. Show the wrong result. Then reset to 45 and apply both changes with atomic updates, showing the right result.
Show solution
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
UPDATE study_totals SET minutes = 45 + 30 WHERE student_id = 103;
UPDATE study_totals SET minutes = 45 + 60 WHERE student_id = 103;
SELECT minutes AS lost_update FROM study_totals;
UPDATE study_totals SET minutes = 45 WHERE student_id = 103;
UPDATE study_totals SET minutes = minutes + 30 WHERE student_id = 103;
UPDATE study_totals SET minutes = minutes + 60 WHERE student_id = 103;
SELECT minutes AS atomic_updates FROM study_totals;CREATE TABLE
INSERT 0 1
UPDATE 1
UPDATE 1
lost_update
-------------
105
(1 row)
UPDATE 1
UPDATE 1
UPDATE 1
atomic_updates
----------------
135
(1 row)The stale writes give 105; the atomic updates give the correct 135. On a real server with two sessions, the second fix is SELECT minutes ... FOR UPDATE before computing the new value, which makes the second session wait and then read 75.
Key Takeaways
| You want to | Write |
|---|---|
| Change a value safely | UPDATE t SET n = n + 30 WHERE ... |
| Lock before reading | SELECT ... FOR UPDATE |
| Don't wait for a lock | SELECT ... FOR UPDATE NOWAIT |
| Optimistic check | UPDATE ... SET version = version + 1 WHERE id = ? AND version = ? |
Was this tutorial helpful?