pg_stat_activity
PG 8.0+ (enhanced in each major version: wait_event/wait_event_type added PG 9.6, backend_type PG 10, query_id PG 14)→ setof recordSystem view showing one row per server process, with information about the current activity: database, user, query text, wait events, state, and timing.
Signature
SELECT * FROM pg_stat_activityExamples
SELECT pid, usename, state, left(query, 80) FROM pg_stat_activity WHERE state != 'idle';All active (non-idle) connections and their queriesSELECT pid, now() - query_start AS duration, query FROM pg_stat_activity WHERE state = 'active' ORDER BY duration DESC;Longest-running queriesSELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE wait_event IS NOT NULL GROUP BY 1, 2 ORDER BY 3 DESC;Current wait event distributionCombine `pg_stat_activity` with `pg_blocking_pids(pid)` to find what is blocking a waiting query: `SELECT pid, pg_blocking_pids(pid) AS blocked_by, query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0`.
SELECT a.pid, a.query, b.pid AS blocking_pid, b.query AS blocking_query FROM pg_stat_activity a JOIN pg_stat_activity b ON b.pid = ANY(pg_blocking_pids(a.pid));Blocked query paired with the query blocking it