What is deadlock in MySQL and how do you prevent it?
Answer
A deadlock occurs when two or more transactions are each waiting for a lock held by the other, creating a circular dependency — neither can proceed. InnoDB detects deadlocks and automatically rolls back one of the transactions (the "victim" — typically the one with the fewest changes, making it cheaper to roll back). The application must handle the error and retry the transaction. Viewing deadlock info: SHOW ENGINE INNODB STATUS\G — shows the last detected deadlock. Prevention strategies: (1) Consistent lock ordering: always acquire locks in the same order across all transactions — if transaction A locks users then orders, transaction B must do the same; (2) Keep transactions short: long transactions hold locks longer, increasing collision probability; (3) Use lower isolation levels: READ COMMITTED acquires fewer locks than REPEATABLE READ; (4) Use SELECT ... FOR UPDATE only when necessary; (5) Process rows in a consistent order: ORDER BY in SELECT...FOR UPDATE queries; (6) Avoid user interaction inside transactions; (7) Use SELECT ... SKIP LOCKED (MySQL 8.0+) for queue processing to avoid competing for locked rows; (8) Application retry logic: catch deadlock errors (MySQL error 1213) and retry with exponential backoff.
Previous
What is the InnoDB Buffer Pool and how does it work?
Next
What is the query execution plan and how does the MySQL optimizer work?
More MySQL / SQL Questions
View all →- Advanced What is the difference between B-tree and Hash indexes in MySQL?
- Advanced What is MVCC (Multi-Version Concurrency Control) in MySQL?
- Advanced What is the InnoDB Buffer Pool and how does it work?
- Advanced What is the query execution plan and how does the MySQL optimizer work?
- Advanced What is the difference between optimistic locking with version numbers and timestamps?