Skip to content

Instantly share code, notes, and snippets.

@mcorsen
Created June 6, 2014 16:22
Show Gist options
  • Save mcorsen/b67c2524dc4ab23a3fe1 to your computer and use it in GitHub Desktop.
Save mcorsen/b67c2524dc4ab23a3fe1 to your computer and use it in GitHub Desktop.
Postgresql 9.1 query to find queries that are blocked by locks
SELECT
l1.relation::regclass AS blocked_relation,
l1.pid AS blocked_pid,
a1.usename AS blocked_user,
a1.current_query AS blocked_query,
now() - a1.query_start AS blocked_time,
l2.pid AS blocking_pid,
a2.usename AS blocking_user,
a2.current_query AS blocking_query,
l2.virtualtransaction,
l2.mode,
l2.granted
FROM
pg_locks l1
JOIN
pg_locks l2 ON (
(
l1.locktype,
l1.DATABASE,
l1.relation,
l1.page,
l1.tuple,
l1.virtualxid,
l1.transactionid,
l1.classid,
l1.objid,
l1.objsubid
)
IS NOT DISTINCT FROM
(
l2.locktype,
l2.DATABASE,
l2.relation,
l2.page,
l2.tuple,
l2.virtualxid,
l2.transactionid,
l2.classid,
l2.objid,
l2.objsubid
)
)
JOIN pg_stat_activity a1 ON a1.procpid = l1.pid
JOIN pg_stat_activity a2 ON a2.procpid = l2.pid
WHERE
NOT l1.granted
AND
l2.granted
ORDER BY blocked_time DESC
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment