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.
Code
-- 谁在阻塞谁: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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- The references are `pg_stat_activity`, `pg_locks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.