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.
Code
-- 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
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.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.
FAQ
- Which tables appear in this script?
- The references are `pg_stat_activity`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.