Locks and Deadlocks

Updated · 10 min read
hardPostgreSQL 18sqllocksselect-for-updatedeadlockoptimistic-lockinginterview

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

  • UPDATE and DELETE lock the rows they change until COMMIT or ROLLBACK; other writers of those rows wait.
  • Plain SELECT takes no row locks: reading a row never blocks changing it, and changing a row never blocks reading it. (A SELECT does make schema changes like ALTER TABLE wait.)
  • SELECT ... FOR UPDATE locks 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 version column 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:

SQL▶ Try it
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;
Output
BEGIN
 
UPDATE 1
 
       mode       | table_name
------------------+------------
 RowExclusiveLock | courses
(1 row)
 
ROLLBACK

Explanation: 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.

StatementTable lockRow lockBlocks
SELECTAccessSharenoneOnly DROP and similar schema changes
SELECT ... FOR UPDATERowSharethe selected rowsOther updates and FOR UPDATE of those rows
INSERT, UPDATE, DELETERowExclusivethe changed rowsOther updates of those rows
ALTER TABLE, DROP TABLE, LOCK TABLEAccessExclusiveEverything 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:

SQL▶ Try it
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;
Output
BEGIN
 
   title    | fee_usd
------------+---------
 SQL Basics |  400.00
(1 row)
 
     mode     | locked_object
--------------+---------------
 RowShareLock | courses
 RowShareLock | courses_pkey
(2 rows)
 
COMMIT

Explanation: 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:

SQL▶ Try it
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;
Output
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:

SQL▶ Try it
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;
Output
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.

Both sessions read 45 and the last write wins with 105; an atomic update or FOR UPDATE gives 135

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.

SQL▶ Try it
SHOW deadlock_timeout;
Output
 deadlock_timeout
------------------
 1s
(1 row)
A holds course 1 and wants course 2; B holds course 2 and wants course 1; PostgreSQL cancels one

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:

SQL▶ Try it
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;
Output
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.

Who Waits for Whom

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
SQL▶ Try it
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;
Output
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.

Quick check: Locks and deadlocks

3 questions
1Session A updates course 4 and hasn't committed. Session B runs SELECT on course 4. What happens?
2Which fixes a lost update?
3What does PostgreSQL do when it detects a deadlock?

Key Takeaways

You want toWrite
Change a value safelyUPDATE t SET n = n + 30 WHERE ...
Lock before readingSELECT ... FOR UPDATE
Don't wait for a lockSELECT ... FOR UPDATE NOWAIT
Optimistic checkUPDATE ... SET version = version + 1 WHERE id = ? AND version = ?

Was this tutorial helpful?

Lesson 77 of 115