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.