Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 147/ 160
08. Transactions, Security & Production SQL Administration

Understanding, Detecting & Preventing Deadlocks

Detect deadlock cycles and prevent them with consistent lock ordering.

AdvancedDeadlock Cycle · Detection3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Two transactions each wait for something the other is holding, forever. The database spots it and cancels one so the other can finish.

Think of it like…

Two cars meet on a narrow bridge from opposite ends; each needs the other to back up. Someone has to reverse (the database aborts one transaction) before either can cross.

Where you’ve seen it

Two transfers run at once: T1 moves money from account 1 to 2, T2 from account 2 to 1. T1 locks account 1, T2 locks account 2, then each tries to lock the other. Updating accounts in ascending id order in every transfer makes the cycle impossible.

Words you’ll hear

Lock wait
A transaction blocked until another releases a lock; normal and temporary.
Deadlock cycle
T1 waits for T2 while T2 waits for T1; it can never resolve itself.
Deadlock detection
The database periodically checks waiting transactions for cycles and aborts a victim.
Lock ordering
Always acquiring locks in the same global order, which prevents cycles.

Visual diagram

Loading interactive diagram

Theory & example queries

How deadlocks form and get resolved

A deadlock needs at least two transactions acquiring the same locks in different orders. Each succeeds with its first lock, then blocks on a lock the other already holds. Unlike a normal lock wait, nothing will ever release, because each is waiting on the other.

Databases detect this automatically. PostgreSQL checks for cycles after a transaction has waited for deadlock_timeout (1 second by default), then aborts one participant with "deadlock detected". InnoDB detects them immediately. The error is your signal to roll back and retry the whole transaction.

Reproducing oneQuery example
1Input dataStart from the source rows or state that the statement sees.
accounts
2 rows
accounts sample rows
idownerbalance
1Maya1000
2Ravi500
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23UPDATE accounts4SET5  balance = balance - 1006WHERE7  id = 1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/7
query.sql
1BEGIN;23UPDATE accounts4SET5  balance = balance - 1006WHERE7  id = 2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/7
query.sqlReadable preview
1UPDATE accounts …2WHERE id = 2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/2
query.sqlReadable preview
1UPDATE accounts …2WHERE id = 1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/2
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ERROR: deadlock detected DETAIL: Session 2 waited while updating account 1; the transaction is aborted as the victim.

Note: Representative PostgreSQL result; lock-wait wording and which session is rolled back are engine- and timing-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Session 1:

Session 2:

Session 1:

(waits) Session 2:

→ deadlock detected.

Key takeaway: Different lock orders plus concurrency create cycles; the database breaks them by aborting one.

Preventing and handling them

Acquire locks in a consistent order everywhere: for transfers, lock or update the lower account id first, regardless of direction. When a transaction will touch several rows, lock them all up front with SELECT … WHERE id IN (…) ORDER BY id FOR UPDATE. Keep transactions short, never wait for user input inside one, and index foreign key columns so checks don't lock or scan more rows than necessary.

Even with good design, rare deadlocks can still happen under load, so treat them like serialization failures: catch the error and retry the transaction a few times with a short backoff. Investigate with PostgreSQL's server log (which records the statements involved) or MySQL's SHOW ENGINE INNODB STATUS (LATEST DETECTED DEADLOCK).

Consistent order for a transferQuery example
1Input dataStart from the source rows or state that the statement sees.
accounts
2 rows
accounts sample rows
idownerbalance
1Maya1000
2Ravi500
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1SELECT id2FROM accounts3WHERE id IN ($from, $to)4ORDER BY id FOR5UPDATE;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
id
1
2

Note: Illustrative result for $from = 2 and $to = 1; the selected rows are locked in ascending ID order.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then perform both UPDATEs. Every transfer locks the lower id first, so two transfers can't lock in opposite orders.

Key takeaway: Consistent ordering prevents most deadlocks; retries handle the rest.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Logs

Find the transactions involved

Read the deadlock report in the PostgreSQL log or SHOW ENGINE INNODB STATUS to see which statements and rows were in the cycle.

Focus at this step

ERROR: deadlock detected

What to watch at this step
PostgreSQL
40P01
MySQL
1213
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A deadlock happens when two (or more) transactions each hold a lock the other needs, so neither can continue. The database detects the cycle, aborts one transaction with an error (PostgreSQL SQLSTATE 40P01, MySQL error 1213), and lets the other finish. The aborted transaction must be retried.

Why it matters: Deadlocks show up under real concurrency, typically as intermittent errors in production that never happen in testing. You can't eliminate the possibility entirely, but consistent lock ordering and short transactions make them rare, and retry logic makes them harmless. It's a standard question for backend and database roles.

When to reach for it

  • Money transfers and other two-row updates
  • Batch jobs that update many rows while users write too
  • Diagnosing intermittent "deadlock detected" errors

When to avoid or be careful

  • Updating related rows in whatever order the request happens to list them
  • Long transactions that mix reads, external calls and writes
  • Ignoring deadlock errors instead of retrying

Deadlock prevention techniques

Consistent lock ordering
Best for: Any code that locks several rows or tables

Strengths: Removes the cycle that causes most deadlocks.

Watch out: Every code path has to follow the same rule.

Short transactions, locks taken up front
Best for: Busy tables with many concurrent writers

Strengths: Fewer and shorter lock overlaps.

Watch out: May lock rows slightly earlier than strictly needed.

Retry on deadlock error
Best for: Every application that writes concurrently

Strengths: Makes the rare remaining deadlocks invisible to users.

Watch out: Doesn't fix frequent deadlocks; hides design problems if overused.

Interview signals & numbers to know

When this topic comes up

  • "deadlock detected" in logs
  • Intermittent failures under load
  • “What is a deadlock and how do you prevent it?”
  • Transfers between accounts
  • Concurrent batch updates

Benchmarks & rules of thumb

40P01 -
PostgreSQL deadlock SQLSTATE
1213 -
MySQL deadlock error code
1 s -
PostgreSQL default deadlock_timeout

Common mistakes & follow-ups

Common interview mistakes

  • Confusing a long lock wait with a deadlock; waits resolve, deadlocks don't.
  • Locking the source account first in a transfer, so opposite-direction transfers deadlock.
  • Treating a deadlock error as fatal instead of retrying the transaction.

Likely interviewer follow-ups

  • How would you prevent deadlocks between concurrent money transfers?
  • What's the difference between a lock wait and a deadlock?
  • How do you find out which queries were involved in a deadlock?
Interview tip: Use the two-transfer example, fix it with consistent ordering by account id, and mention retries. It's concrete, and it shows you know deadlocks are managed rather than eliminated.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Understanding, Detecting & Preventing Deadlocks with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Table-Level Locks & Advisory Locks
Next topic
Multi-Version Concurrency Control (MVCC) & Table Bloat