📖 Scenario: You are managing a small online bookstore database. Sometimes, when multiple users try to update orders and inventory at the same time, the database gets stuck due to deadlocks. You want to learn how to detect and prevent these deadlocks using MySQL commands and transaction control.
🎯 Goal: Build a simple MySQL setup with two tables and transactions that can cause deadlocks. Then, learn how to detect deadlocks and apply prevention techniques by controlling transaction order and using proper locking.
📋 What You'll Learn
Create two tables: orders and inventory with specified columns
Insert initial data into both tables
Write two transactions that update orders and inventory in opposite order to simulate deadlock
Use MySQL commands to detect deadlocks
Modify transactions to prevent deadlocks by consistent locking order
💡 Why This Matters
🌍 Real World
Deadlocks can freeze database operations in real applications like online stores, banking systems, or booking platforms. Detecting and preventing deadlocks keeps the system responsive and reliable.
💼 Career
Database administrators and backend developers must understand deadlocks to maintain data integrity and system performance in multi-user environments.
Progress0 / 4 steps
1
Create tables and insert initial data
Create a table called orders with columns order_id INT PRIMARY KEY and product_id INT. Create another table called inventory with columns product_id INT PRIMARY KEY and stock INT. Insert one row into orders with order_id = 1 and product_id = 101. Insert one row into inventory with product_id = 101 and stock = 50.
MySQL
Hint
Use CREATE TABLE statements for both tables. Then use INSERT INTO to add one row each.
2
Write transactions that cause deadlock
Write two transactions. The first transaction updates orders setting product_id = 102 where order_id = 1, then updates inventory reducing stock by 1 for product_id = 101. The second transaction updates inventory reducing stock by 1 for product_id = 101, then updates orders setting product_id = 102 where order_id = 1. Use START TRANSACTION and COMMIT for both. This setup can cause a deadlock.
MySQL
Hint
Use two separate transactions with START TRANSACTION and COMMIT. The first updates orders then inventory. The second updates inventory then orders.
3
Detect deadlocks using MySQL commands
Use the MySQL command SHOW ENGINE INNODB STATUS; to detect deadlocks after running the transactions. Assign the output to a variable called deadlock_info for analysis.
MySQL
Hint
Use SHOW ENGINE INNODB STATUS; to see deadlock details. Assign the result to a variable named deadlock_info for further checking.
4
Prevent deadlocks by consistent locking order
Modify the two transactions so both update orders first, then inventory. Use START TRANSACTION and COMMIT for both. This consistent order prevents deadlocks.
MySQL
Hint
Make sure both transactions update orders first, then inventory. This consistent order avoids deadlocks.
Practice
(1/5)
1. What is a deadlock in MySQL InnoDB storage engine?
easy
A. A type of backup failure during database replication.
B. A syntax error in SQL queries causing transaction failure.
C. A temporary network disconnection between client and server.
D. A situation where two or more transactions wait indefinitely for each other to release locks.
Solution
Step 1: Understand transaction locking
Transactions acquire locks on data to ensure consistency. If two transactions wait for each other's locks, progress stops.
Step 2: Define deadlock
This waiting cycle with no resolution is called a deadlock, causing transactions to block indefinitely.
Final Answer:
A situation where two or more transactions wait indefinitely for each other to release locks. -> Option D
Quick Check:
Deadlock = Transactions waiting on each other [OK]
Hint: Deadlock means transactions block each other forever [OK]
Common Mistakes:
Confusing deadlock with syntax errors
Thinking deadlock is a network issue
Assuming deadlock is a backup problem
2. Which MySQL command helps you check the latest deadlock information in InnoDB?
easy
A. SHOW PROCESSLIST;
B. SHOW ENGINE INNODB STATUS;
C. SHOW TRANSACTION LOCKS;
D. SHOW DEADLOCKS;
Solution
Step 1: Identify command for deadlock info
MySQL does not have a direct SHOW DEADLOCKS command, but SHOW ENGINE INNODB STATUS shows detailed InnoDB info including deadlocks.
Step 2: Confirm other options
SHOW PROCESSLIST shows running threads, not deadlocks. SHOW TRANSACTION LOCKS is invalid syntax.
Final Answer:
SHOW ENGINE INNODB STATUS; -> Option B
Quick Check:
SHOW ENGINE INNODB STATUS = Deadlock info [OK]
Hint: Use SHOW ENGINE INNODB STATUS for deadlock details [OK]
Common Mistakes:
Using non-existent SHOW DEADLOCKS command
Confusing PROCESSLIST with deadlock info
Trying SHOW TRANSACTION LOCKS which is invalid
3. Consider two transactions T1 and T2 running concurrently: -- T1: START TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- T2: START TRANSACTION; UPDATE accounts SET balance = balance + 100 WHERE id = 2; UPDATE accounts SET balance = balance - 100 WHERE id = 1; What is the likely outcome if both run at the same time without deadlock prevention?
medium
A. A deadlock occurs causing one transaction to be rolled back.
B. Both transactions complete successfully without waiting.
C. Both transactions fail with syntax errors.
D. Transactions run sequentially without any lock conflicts.
Solution
Step 1: Analyze lock acquisition order
T1 locks account id=1 first, then id=2. T2 locks id=2 first, then id=1. This creates a circular wait.
Step 2: Identify deadlock
Because each transaction waits for the other's locked row, a deadlock occurs. MySQL detects this and rolls back one transaction.
Final Answer:
A deadlock occurs causing one transaction to be rolled back. -> Option A
Quick Check:
Opposite lock order = Deadlock and rollback [OK]
Hint: Opposite lock order in transactions causes deadlock [OK]
Common Mistakes:
Assuming both transactions succeed without conflict
Thinking syntax errors cause failure
Believing transactions run sequentially automatically
4. You have this MySQL transaction code causing deadlocks: START TRANSACTION; UPDATE products SET stock = stock - 1 WHERE id = 10; UPDATE orders SET status = 'processed' WHERE id = 100; COMMIT; How can you fix deadlocks by changing the transaction?
medium
A. Keep transactions short and access tables in the same order everywhere.
B. Add a LOCK TABLES statement before updates.
C. Use multiple COMMIT statements inside the transaction.
D. Disable autocommit mode.
Solution
Step 1: Understand deadlock causes
Deadlocks often happen when transactions lock tables in different orders or run too long holding locks.
Step 2: Apply prevention best practice
Keeping transactions short and always locking tables in the same order prevents circular waits and deadlocks.
Final Answer:
Keep transactions short and access tables in the same order everywhere. -> Option A
Hint: Short, consistent lock order avoids deadlocks [OK]
Common Mistakes:
Thinking LOCK TABLES solves deadlocks alone
Using multiple COMMITs inside one transaction
Confusing autocommit disabling with deadlock fix
5. You want to prevent deadlocks in a high-traffic MySQL application. Which combination of strategies is best?
1. Keep transactions short
2. Set innodb_lock_wait_timeout to a low value
3. Use consistent lock order in all transactions
4. Disable foreign key constraints
hard
A. 1 and 4 only
B. 2 and 4 only
C. 1, 2, and 3 only
D. All four strategies
Solution
Step 1: Evaluate each strategy
Keeping transactions short and consistent lock order reduce deadlocks. Setting a low innodb_lock_wait_timeout helps detect and abort deadlocks quickly.
Step 2: Assess disabling foreign keys
Disabling foreign keys can cause data integrity issues and does not prevent deadlocks effectively.
Final Answer:
1, 2, and 3 only -> Option C
Quick Check:
Short, timeout, order = Deadlock prevention [OK]
Hint: Short transactions + timeout + lock order prevent deadlocks [OK]
Common Mistakes:
Disabling foreign keys to prevent deadlocks
Ignoring lock wait timeout settings
Not enforcing consistent lock order
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.