# Postgres error 40P01: deadlock detected

> Two or more transactions each held a lock the other needed. Postgres cancelled one of them to break the cycle.

Source: https://scribase.com/postgres-errors/40p01

SQLSTATE class: Transaction Rollback. Over PostgREST/supabase-js this maps to HTTP 500.

## Causes

- Transactions that update the same rows in different orders.
- Foreign key checks taking share locks on parent rows while another transaction updates them.
- Long transactions that mix many writes.

## Fixes

- Retry the cancelled transaction.
- Always lock or update rows in a consistent order (for example sorted by id).
- Lock what you need up front with SELECT ... FOR UPDATE in that order, and keep transactions short.

## Example

```sql
-- update a batch in a stable order so concurrent batches cannot deadlock
update inventory i set qty = qty - o.qty
from (select sku, qty from order_lines where order_id = $1 order by sku) o
where i.sku = o.sku;
```