# Deadlock found when trying to get lock; try restarting transaction

**Code:** `Deadlock` · **Category:** SQL · **Seen on:** MySQL, PostgreSQL

Two transactions waited on each other’s locks; the database killed one so the other could continue.

## Meaning

Deadlocks are normal in busy OLTP systems. The database picks a victim and rolls it back (MySQL 1213, PostgreSQL 40P01, SQL Server 1205). Applications should retry the victim transaction — and reduce how often it happens.

## Common causes

- Transactions updating the same rows in different orders
- Long transactions holding locks
- Missing indexes causing range/gap locks on many rows
- Bulk updates competing with OLTP writes

## Quick fix

1. Retry the transaction (with small backoff) on deadlock errors
2. Access tables/rows in a consistent order
3. Keep transactions short
4. Add indexes so updates lock fewer rows

## Detailed fix by platform

### MySQL

1. `SHOW ENGINE INNODB STATUS\G` → LATEST DETECTED DEADLOCK shows both queries.

### PostgreSQL

1. Enable `log_lock_waits` and check the server log for the deadlock detail.

## How to diagnose

1. **Queries** — Which two statements deadlocked?
2. **Order** — Do they lock rows in different orders?
3. **Indexes** — Are WHERE clauses indexed?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/sql/deadlock-found)
