# Locks & Deadlocks

> Learn how row locks make writers wait, why readers do not, how two sessions can block each other forever, and how to prevent it.

Subject: SQL | Lesson 34 of 44 | 6 min read
Interactive lesson: https://codewithanimation.in/sql/locks-and-deadlocks
Previous: [Isolation Levels](https://codewithanimation.in/sql/isolation-levels.md) | Next: [CREATE, ALTER & DROP TABLE](https://codewithanimation.in/sql/create-alter-drop-tables.md)

## A row you change is locked until you finish

When a transaction updates or deletes a row, PostgreSQL puts a **row lock** on it. Any other transaction that wants to change the same row has to **wait** until the first one commits or rolls back.

Row locks only block writers. A plain `SELECT` is never blocked by them, and never blocks anyone: it simply reads the last committed version of the row.

## Locks keep changes from colliding

Without a lock, two sessions could both read a balance of 100 and each write back their own total, and one of the changes would be lost. The lock makes the second one wait and then work with the new value.

## Waiting is normal

Session A runs `UPDATE accounts SET balance = balance + 10 WHERE name = 'Alice'` inside a transaction. Session B runs the same statement on the same row. B waits. When A commits, B's update runs.

If both sessions touch the rows in the same order, Alice first and then Bob, the second one only waits for a while and everything finishes.

A reader meets a writer: B has updated Alice but not committed, and A runs a `SELECT` on Alice. A gets the last committed value at once. It does not wait.

## Common mistake: Deadlock: waiting for each other

Now take opposite orders. A updates Alice and then wants Bob. B updates Bob and then wants Alice. A waits for B, and B waits for A. Neither can ever continue. That is a **deadlock**.

PostgreSQL notices. After `deadlock_timeout` (1 second by default) it checks for a loop, aborts one of the transactions with `ERROR: deadlock detected` (SQLSTATE 40P01) and lets the other finish. Which one is aborted is hard to predict, so never rely on it.

The aborted transaction must be retried by your application. Waiting also has a cost: long transactions keep their locks for a long time and make other sessions queue.

## Tip: Same order, short transactions, retry on 40P01

Always touch rows in the same order, for example by id, in every part of your program. Keep transactions short, and never wait for a user inside one. If a deadlock still happens, catch SQLSTATE 40P01 and retry the transaction.

## Try it: Watch the locks

Run Opposite order and look at the waits table just before the error. Then run Same order, and A reader meets a writer.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/locks-and-deadlocks

## Check yourself

### Question 1

Session A has updated a row and not yet committed. Session B runs a plain SELECT on that row. What happens?

- A. B reads the last committed value immediately
- B. B waits until A commits
- C. B gets an error

Correct answer: A

Readers do not block writers and writers do not block readers. B sees the committed version.

- Why not B: Row locks do not block readers. They only block other writers.
- Why not C: A plain read never fails because of someone else's row lock.

### Question 2

A updates Alice then wants Bob. B updates Bob then wants Alice. What does PostgreSQL do?

- A. It detects the deadlock and aborts one of the two transactions
- B. Both wait forever
- C. It aborts both transactions

Correct answer: A

The manual says PostgreSQL resolves a deadlock by aborting one of the transactions involved, so the others can complete.

- Why not B: PostgreSQL checks for deadlocks automatically, after deadlock_timeout.
- Why not C: One transaction is aborted so the other can finish.

### Question 3

What is the best way to prevent deadlocks between transactions that update several rows?

- A. Lock and update the rows in the same order everywhere
- B. Make transactions as long as possible
- C. Raise the isolation level

Correct answer: A

If every transaction takes locks in the same order, a loop of waiting cannot form.

- Why not B: Long transactions hold locks longer, which makes deadlocks and waiting worse.
- Why not C: A higher level does not remove row lock conflicts. The manual's advice is a consistent lock order.

## Remember this

- An UPDATE or DELETE locks the row until the transaction ends, and other writers wait.
- Readers never wait for writers, and writers never wait for readers.
- Two sessions waiting for each other is a deadlock. PostgreSQL aborts one with deadlock detected (40P01), and you retry it.
- Prevent deadlocks: update rows in the same order, keep transactions short.
