Blocking Sessions With pg_blocking_pids

List the sessions waiting on locks with pg_blocking_pids joined against pg_stat_activity, then inspect pg_locks for the exact lock modes they are stuck on.

SqlData Integrity

Code

snippet
-- 谁在阻塞谁:pg_blocking_pids 返回挡住该会话的会话 PID 列表
-- 会话必须真的在等待锁,函数才返回非空
SELECT
    pid,
    usename,
    state,
    wait_event_type,
    wait_event,
    query,
    pg_blocking_pids(pid) AS blocked_by,
    cardinality(pg_blocking_pids(pid)) AS blocker_count
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
ORDER BY blocker_count DESC;

-- 结合 pg_locks 看具体未授予的锁类型与模式
SELECT
    pid,
    locktype,
    mode,
    granted
FROM pg_locks
WHERE NOT granted
ORDER BY pid;

-- 人工干预:结束阻塞链顶端的会话
-- SELECT pg_terminate_backend(<pid>);

How it works

SELECT statements share the script, touching pg_stat_activity and pg_locks.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order.

Using it

Run the statement against the pg_stat_activity table.

Key statements

SELECT
    pid,
    usename,
    state,
    wait_event_type,
    wait_event,
    query,
    pg_blocking_pids(pid) AS blocked_by,
    cardinality(pg_blocking_pids(pid)) AS blocker_count
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
ORDER BY blocker_count DESC;
SELECT
    pid,
    locktype,
    mode,
    granted
FROM pg_locks
WHERE NOT granted
ORDER BY pid;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `pg_stat_activity`, `pg_locks`.