pg_backend_pid Session Identification

pg_backend_pid returns the process ID of the server process attached to the current session, matching the pid column in pg_stat_activity and lock diagnostics.

SqlCli Tooling

Code

snippet
-- 当前会话的后端进程 ID:pg_stat_activity.pid 与锁诊断用的是同一编号
SELECT pg_backend_pid() AS my_pid;

-- 用它锁定 pg_stat_activity 里自己那一行
SELECT pid, state, application_name
FROM pg_stat_activity
WHERE pid = pg_backend_pid();

-- 与 pg_blocking_pids 配对:谁在挡我这个会话(通常为空数组)
SELECT pg_blocking_pids(pg_backend_pid()) AS blocking_me;

-- 每个连接的 PID 不同:不同会话拿到不同值
-- (psql 会话 A)SELECT pg_backend_pid();  -- 例如 12345
-- (psql 会话 B)SELECT pg_backend_pid();  -- 例如 12401

-- 应用场景:把 PID 写进应用日志,慢查询/锁等待时能对上
-- pg_stat_activity 里 state='active' 且 wait_event 非空的行

How the snippet works

The file runs SELECT statements, touching pg_stat_activity.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch.

Using it

The pg_stat_activity table is the working surface here.

Key statements

SELECT pid, state, application_name
FROM pg_stat_activity
WHERE pid = pg_backend_pid();
SELECT pg_blocking_pids(pg_backend_pid()) AS blocking_me;
SELECT pg_backend_pid() AS my_pid;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`pg_stat_activity` — referenced directly, no join needed.