40P01: deadlock_detected
PostgreSQLWhat does it mean?
Two or more transactions entered a deadlock by each waiting for locks held by the other. PostgreSQL detects the cycle and cancels one of the transactions.
Why does it happen?
Locks acquired in different orders, cross updates of the same rows, long transactions, or conflicting locks taken during foreign key checks.
How to fix it
The deadlock detail in the server log shows the conflicting queries. Access tables/rows in the same order in all transactions. Keep transactions short. Catch the cancelled transaction in the application and retry it. Join pg_locks with pg_stat_activity to examine locks. If needed, make the lock order explicit with SELECT ... FOR UPDATE.