Skip to content

Instantly share code, notes, and snippets.

@Jeetah
Last active July 19, 2021 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeetah/3ff315cebc81cfd7fc3cd91499d06dfc to your computer and use it in GitHub Desktop.
Save Jeetah/3ff315cebc81cfd7fc3cd91499d06dfc to your computer and use it in GitHub Desktop.
Postgres: Deadlocks (list details of blocking and blocked)
with ld as (
select pid, array_agg(lock_detail) as lock_details
from (
select l.pid, concat(l.mode, ' on ', l.locktype, ' (Table: ', t.relname,')') as lock_detail
from pg_catalog.pg_locks l
left outer join pg_stat_all_tables t on t.relid = l.relation
where t.relname not like 'pg_%'
) as details
group by pid
)
SELECT
bl.pid AS blocked_pid,
bl.mode as blocked_lock_type,
bld.lock_details as blocked_locks_details,
a.client_addr as blocked_IP,
a.application_name AS blocked_app,
a.usename AS blocked_user,
ka.client_addr as blocking_IP,
kl.pid AS blocking_pid,
kl.mode as blocking_lock_type,
kld.lock_details as blocking_locks_details,
ka.application_name as blocking_app,
ka.usename AS blocking_user,
a.query AS blocked_statement,
ka.query as last_statement_from_blocking_tx,
a.query_start as start_of_blocked,
round(EXTRACT(EPOCH FROM (now() - a.query_start))) as age_of_blocked, --start of current tx
ka.query_start as start_of_blocking,
round(EXTRACT(EPOCH FROM (now() - ka.query_start))) as age_of_blocking, --start of current tx
a.state as blocked_state,
ka.state as blocking_state
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
join ld as bld on bld.pid = bl.pid
join ld as kld on kld.pid = kl.pid
WHERE NOT bl.granted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment