Deadlocks — Complete Guide
Deadlocks — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 35 of 100
Deadlocks
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — Transactions & MVCC
What is this?
Deadlock is when two transactions wait on each other locks — PostgreSQL detects the cycle and aborts one with error 40P01. The other continues.
Why should you care?
PostgresVerse wallet transfer from A→B and B→A simultaneously can deadlock if each locks accounts in opposite order.
See it live — copy this example
Run in pgAdmin or psql.
-- Session A -- Session B
BEGIN; BEGIN;
UPDATE accounts SET balance=balance-10 WHERE account_id=1;
UPDATE accounts SET balance=balance-10 WHERE account_id=2;
UPDATE accounts SET balance=balance+10 WHERE account_id=2;
UPDATE accounts SET balance=balance+10 WHERE account_id=1;
-- one session gets: ERROR: deadlock detected
What happened?
- A locks account 1 then waits for 2.
- B locks 2 then waits for 1.
- Postgres picks a victim and rolls back that transaction.
Practice next
- Open two psql sessions on PostgresVerse.
- Run steps in parallel as shown.
- Read deadlock detected message and which pid was victim.
- Fix by always updating lower account_id first in both sessions.
- Query pg_locks during staged deadlock to see wait edges.
Remember
Deadlock is normal under contention — detect and retry. Lock resources in consistent global order. Keep lock-holding transactions short.
PostgresVerse P2P transfer
Mobile app retries transfer once on 40P01; consistent lock order on account ids.
Outcome: Deadlock rate drops from 0.3% to negligible.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!