pg_stat_activity Active Query Duration

Snapshot pg_stat_activity to see which queries are active, how long each has run, and which sessions sit idle in transaction.

SqlResilience

Code

snippet
-- pg_stat_activity snapshot: who is running, for how long, and from which client
SELECT pid,
       usename,
       application_name,
       state,
       now() - query_start AS running_for,
       left(query, 60) AS query_head
FROM pg_stat_activity
WHERE state = 'active'
  AND pid <> pg_backend_pid()
ORDER BY running_for DESC;

-- active queries over 5 minutes: sort by duration to locate the slow ones
SELECT pid,
       now() - query_start AS running_for,
       left(query, 60) AS query_head
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > INTERVAL '5 minutes'
ORDER BY running_for DESC;

-- sessions stuck inside a transaction: idle in transaction holds locks and connection slots indefinitely
SELECT pid,
       usename,
       now() - state_change AS idle_for,
       left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY idle_for DESC;

Inside the snippet

SELECT statements share the script, touching pg_stat_activity.

Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order.

Putting it to use

The pg_stat_activity table is the working surface here.

Lines that hold the logic

SELECT pid,
       usename,
       application_name,
       state,
       now() - query_start AS running_for,
       left(query, 60) AS query_head
FROM pg_stat_activity
WHERE state = 'active'
  AND pid <> pg_backend_pid()
ORDER BY running_for DESC;
SELECT pid,
       now() - query_start AS running_for,
       left(query, 60) AS query_head
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > INTERVAL '5 minutes'
ORDER BY running_for DESC;
SELECT pid,
       usename,
       now() - state_change AS idle_for,
       left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY idle_for DESC;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `pg_stat_activity`.