dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/postgresql/#2
Script #2
postgresql
Lockingread-onlyMin Version: 9.6

PostgreSQL Lock Chain: Who Is Blocking Whom?

Uses pg_blocking_pids to pair blocked and blocking sessions with their queries and wait times. Shows the root cause of a lock chain in seconds.

#locks#blocking#pg_blocking_pids#deadlock
postgresql · sql
SELECT blocked.pid                AS blocked_pid,
       blocked.usename            AS blocked_user,
       left(blocked.query, 120)   AS blocked_query,
       blocker.pid                AS blocking_pid,
       blocker.usename            AS blocking_user,
       blocker.state              AS blocking_state,
       left(blocker.query, 120)   AS blocking_query,
       now() - blocked.query_start AS waiting_for
FROM pg_stat_activity blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity blocker ON blocker.pid = b.pid
ORDER BY waiting_for DESC;
Operational Notes & Remediation Guidance

The PID at the very top of the chain (not blocked by any other session) is the root cause blocker.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 9.6).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.