Deadlock
- SQL course
- Advanced
- Lesson 62/81
- 4 min
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 → deadlockMutual 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
-- prevent deadlock
SELECT * FROM accounts WHERE id = 1Sample solution
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
____ → mutual waiting
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.