What is a deadlock in databases and how is it resolved?
Answer
A deadlock occurs when two or more transactions each hold a lock that the other needs, causing them to wait indefinitely. Example: Transaction A locks row 1 and wants row 2; Transaction B locks row 2 and wants row 1. Neither can proceed. Databases detect deadlocks automatically using a wait-for graph and resolve them by killing one transaction (the "deadlock victim") and rolling it back. Prevention strategies: consistent lock ordering (always lock resources in the same order), keep transactions short (minimize lock hold time), use lower isolation levels where appropriate, and lock at coarser granularity. Application code should always handle deadlock errors with a retry loop.
Previous
What is database migration strategy for zero-downtime deployments?
Next
What are database constraints and what types exist?
More Database Design / Normalization Questions
View all →- Intermediate What are database anomalies and how does normalization prevent them?
- Intermediate What is denormalization and when is it used?
- Intermediate What are isolation levels in database transactions?
- Intermediate What are dirty reads, non-repeatable reads, and phantom reads?
- Intermediate What is query optimization and what is a query execution plan?