Example: Deadlock Detection and Resolution
The following example demonstrates how a deadlock can occur when two transactions attempt to lock rows in different orders. MySQL’s InnoDB engine will automatically detect this situation and resolve it by rolling back one transaction.
Syntax & Example:
-- Transaction A
START TRANSACTION;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
-- Transaction B
START TRANSACTION;
SELECT * FROM accounts WHERE id = 2 FOR UPDATE;
-- Transaction A waits for row 2
SELECT * FROM accounts WHERE id = 2 FOR UPDATE;
-- Transaction B waits for row 1
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
In this scenario, both transactions wait on each other, creating a deadlock.
InnoDB automatically detects the deadlock and rolls back one of the transactions to allow the other to proceed.