Databases sql Advanced

Deadlock Detection and Prevention

Query Postgres lock waiters and identify deadlock candidates before they occur.

sql
-- Active lock waits
SELECT
  blocked.pid,
  blocked.query AS blocked_query,
  blocking.pid  AS blocking_pid,
  blocking.query AS blocking_query
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
  ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;

-- Kill a blocking query
SELECT pg_terminate_backend(42);

Prerequisites

  • PostgreSQL >= 9.6

Pro Tips

  • → Always acquire locks in the same order across transactions to prevent deadlocks.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
sql
Level
Advanced
Read time
4 min
Published
Jul 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.