This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing one script to find sessions that are blocking other sessions in PostgreSQL.
Instead of finding blocked the sessions or process , sometimes it is better to find sessions that are the root of blocking.
PostgreSQL DBA can use this script to find the root cause of blocking.
pl.pid as blocked_pid
,psa.usename as blocked_user
,pl2.pid as blocking_pid
,psa2.usename as blocking_user
,psa.query as blocked_statement
FROM pg_catalog.pg_locks pl
JOIN pg_catalog.pg_stat_activity psa
ON pl.pid = psa.pid
JOIN pg_catalog.pg_locks pl2
JOIN pg_catalog.pg_stat_activity psa2
ON pl2.pid = psa2.pid
ON pl.transactionid = pl2.transactionid
AND pl.pid != pl2.pid
WHERE NOT pl.granted;