What is deadlock in MySQL and how do you prevent it?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

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.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your MySQL / SQL experience.