SQL & PostgreSQLInterview preparation
Advanced·Concept·2 min read

What is a deadlock, and how do I handle it?

Practice this question

Definition:

A deadlock is a cycle of waiting transactions: each holds a lock another needs to continue. The database detects the cycle and cancels a participant so the others can proceed. Applications must treat that cancellation as a failed transaction and decide whether to retry it.

Key points:

  • Two transactions hold locks that the other needs.

  • The database aborts one transaction to break the cycle.

  • Lock rows in a consistent order, keep transactions short and retry the aborted transaction safely.

  • Do not retry only the last statement of an aborted transaction; begin a fresh transaction for a safe retry.

Interview point:

  • Reduce deadlocks through consistent lock order and short transactions, but still handle them as a possible production outcome.
Adapted from 05_SQL_POSTGRESQL.md · “What is a deadlock, and how do I handle it?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.