PostgreSQL · Session monitoring · DBA-015
How to See Active Sessions and Running Queries in PostgreSQL
See who is connected, which SQL statements are active, and which open transactions deserve a closer look.
The short answer
Query PostgreSQL’s pg_stat_activity view. Filter to client connections that are not simply idle, and look at state, wait_event_type, and query start time. A session that is idle in transaction belongs on your radar even though it is not executing SQL at that moment.
The SQL diagnostic
Run this read-only query against the PostgreSQL environment you are investigating. Interpret the results in the context of your workload and privileges.
SELECT
pid,
usename,
datname,
application_name,
client_addr,
state,
wait_event_type,
wait_event,
CASE WHEN state = 'active'
THEN now() - query_start END AS active_query_age,
now() - xact_start AS transaction_age,
left(query, 160) AS query_preview
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND state <> 'idle'
ORDER BY xact_start NULLS LAST,
query_start NULLS LAST;Based on DBA-015. This version adds wait-event context and labels active-query age separately from transaction age.
How to read the results
active is executing a statement; idle in transaction has an open transaction but no current statement.Why the filter matters: ordinary idle sessions are excluded from this quick view. They still consume connections, so use a connection-pressure diagnostic if you need to count the whole pool.
What you are seeing: the query column shows the current statement for an active session, but the most recent statement for a non-active session. It is not proof that an idle-in-transaction session is still executing that text.
What to check next
- Start with state and wait event. An
activesession waiting on aLockevent is different from an active query consuming CPU. - Look for long-open transactions. Investigate
idle in transactionsessions whose transaction ages are unexpectedly large. - Identify the owning application. Check the username, database and
application_namebefore contacting an application owner. - Move to the right next diagnostic. Use DBA-016 for elapsed queries and transactions, DBA-018 for blocker relationships, or DBA-020 for total connection pressure.
Related DBA tasks
Continue the investigation with these recipes from SQL Recipes for DBAs: DBA-016 (long-running queries and transactions), DBA-018 (blocking sessions), DBA-019 (inspect locks), and DBA-020 (connection pressure).
Continue learning · Baldwin Apps
More practical solutions in SQL Recipes for DBAs
Find engine-specific recipes for sessions, locks, performance, permissions, backups, maintenance, and troubleshooting. Explore the book and its existing companion materials.