CodeBlanks Logo Icon CodeBlanks

Deadlock

Learn the mutual-wait gridlock.

Deadlock

A deadlock is two operations waiting for each other's locks. An unsolvable wait.

-- İşlem 1: A'yı kilitle, B'yi bekle
-- İşlem 2: B'yi kilitle, A'yı bekle → deadlock

Mutual waiting.

Deadlock — details

The database detects a deadlock and sacrifices one operation. The other continues.

The most effective way to reduce deadlocks is to lock tables and rows in the same order in every transaction and keep transactions short.

Practice Deadlock

Write a query that locks resources in the same order to prevent deadlocks.

Starter code

query.sql
-- prevent deadlock
SELECT * FROM accounts WHERE id = 1

Sample solution

query.sql
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

Expected output

id  balance
1   500

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Deadlock: match the terms

Term Meaning
deadlock deadlock
mutual waiting
sacrifice one op
detect automatic

2 Deadlock

Question
____ → mutual waiting
Answer
Deadlock → mutual waiting

Explanation: Deadlock is the right answer.

3 What is a deadlock?

  • Two transactions waiting on each other Correct answer
  • An automatic commit
  • A fast lock
  • An index problem

Explanation: A deadlock is two operations waiting on each other.

All lessons in Advanced