title: How to detect query which holds the lock in Postgres?
body: <p>I want to track mutual locks in postgres constantly.</p>
  
  <p>I came across <a href="https://wiki.postgresql.org/wiki/Lock_Monitoring" rel="noreferrer">Locks Monitoring</a> article and tried to run the following query:</p>
  
  <pre><code>SELECT bl.pid     AS blocked_pid,
       a.usename  AS blocked_user,
       kl.pid     AS blocking_pid,
       ka.usename AS blocking_user,
       a.query    AS blocked_statement
  FROM  pg_catalog.pg_locks         bl
   JOIN pg_catalog.pg_stat_activity a  ON a.pid = bl.pid
   JOIN pg_catalog.pg_locks         kl ON kl.transactionid = bl.transactionid AND kl.pid != bl.pid
   JOIN pg_catalog.pg_stat_activity ka ON ka.pid = kl.pid
  WHERE NOT bl.granted;
  </code></pre>
  
  <p>Unfortunately, it never returns non-empty result set. If I simplify given query to the following form:</p>
  
  <pre><code>SELECT bl.pid     AS blocked_pid,
       a.usename  AS blocked_user,
       a.query    AS blocked_statement
  FROM  pg_catalog.pg_locks         bl
   JOIN pg_catalog.pg_stat_activity a  ON a.pid = bl.pid
  WHERE NOT bl.granted;
  </code></pre>
  
  <p>then it returns queries which are waiting to acquire a lock. But I cannot manage to change it so that it can return both blocked and blocker queries.</p>
  
  <p>Any ideas?</p>