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.
Code
-- 当前会话的后端进程 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
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.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.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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Which tables appear in this script?
- `pg_stat_activity` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.