How To View Active SQL Queries and Connections in PostgreSQL

Updated

PostgreSQL elephant logo

To see what PostgreSQL is running right now, query pg_stat_activity — but with three filters the usual one-liner leaves out:

SELECT pid,
       date_trunc('milliseconds', now() - query_start) AS running_for,
       state, wait_event_type, wait_event,
       left(query, 44) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
  AND pid <> pg_backend_pid()
  AND backend_type = 'client backend'
ORDER BY query_start;

  pid  | running_for  | state  | wait_event_type | wait_event |                    query
-------+--------------+--------+-----------------+------------+----------------------------------------------
 23009 | 00:00:03.998 | active |                 |            | SET max_parallel_workers_per_gather=0; SELEC
(1 row)

pid <> pg_backend_pid() drops your own monitoring query. backend_type = 'client backend' drops autovacuum, the walwriter and the checkpointer. state <> 'idle' keeps sessions that are stuck inside a transaction without running a statement — the ones a plain state = 'active' filter throws away.

The usual one-liner returns a false positive every time

The usual one-liner is SELECT pid, query, state FROM pg_stat_activity WHERE state = 'active';. Run against a server with exactly one slow query, on this machine, it returns two rows:

  pid  |                                 query                                  | state
-------+------------------------------------------------------------------------+--------
 56636 | SELECT pg_sleep(30), count(*) FROM hw_r6_events;                       | active
 56654 | SELECT pid, query, state FROM pg_stat_activity WHERE state = 'active'; | active
(2 rows)

The second row is the query you just typed. It is always there, it is always active, and on a quiet server it is the majority of the result set. Every result on this page came from PostgreSQL 17.10. The false positive above, the lock wait, cancel versus terminate, the truncated query text and the masked rows each need more than one session open; view-active-queries.sh opens them itself against a cluster of its own in a temporary directory, scores each claim PASS or FAIL, and removes the cluster when it exits; whatever PostgreSQL is already running on your machine is left alone.

“active” does not mean “using CPU”

state tells you the backend has a statement in flight. wait_event_type tells you whether it is doing anything. In the lead example above both wait columns are empty — that backend really is burning CPU, and what to do once you have found it is a separate question from finding it. Here is the same query while one session holds a row lock and a second tries to update the same row:

  pid  |        state        | wait_event_type |  wait_event   |                   query
-------+---------------------+-----------------+---------------+--------------------------------------------
 74734 | idle in transaction | Client          | ClientRead    | UPDATE hw_r6_events SET kind='q' WHERE id=
 74743 | active              | Lock            | transactionid | UPDATE hw_r6_events SET kind='r' WHERE id=
(2 rows)

Backend 74743 is active and consuming nothing; it is parked on Lock/transactionid waiting for 74734. Backend 74734 is idle in transaction with Client/ClientRead — the server is waiting on the application, which has an open transaction and has wandered off. That second row is the actual problem, and WHERE state = 'active' hides it.

query_start and state_change are different clocks

query_start is when the current (or last) statement began. state_change is when the backend last entered its current state. For a running query they move together; the moment a query finishes they diverge, and the gap is the query’s duration. A session that ran SELECT pg_sleep(5) inside a transaction and then sat idle, observed eight seconds after it started:

  pid  |        state        | since_query_start | since_state_change |     last_query
-------+---------------------+-------------------+--------------------+---------------------
 65519 | idle in transaction | 00:00:08.015      | 00:00:03.013       | SELECT pg_sleep(5);
(1 row)

So now() - query_start is only a live duration when state = 'active'. For anything else it is the age of a statement that already finished. To hunt idle-in-transaction sessions, use now() - state_change; to hunt long transactions, use now() - xact_start.

The query column is truncated, silently

pg_stat_activity.query is capped at track_activity_query_size, which defaults to 1 kB. Submitting a 1426-character statement to this server and reading it back:

SHOW track_activity_query_size;   -- 1kB

SELECT pid, length(query) AS query_chars, right(query, 12) AS tail
FROM pg_stat_activity WHERE ... ;

  pid  | query_chars |     tail
-------+-------------+--------------
 67760 |        1023 | xxxxxxxxxxxx

1023 characters, and the tail is padding rather than the end of the statement. There is no ellipsis and no warning. If you are matching on query text, or copying a query out to run EXPLAIN on it, raise track_activity_query_size — it needs a server restart.

Cancel versus terminate, and the case where cancel does nothing

pg_cancel_backend(pid) aborts the running statement; the session survives. The victim sees:

ERROR:  canceling statement due to user request

pg_terminate_backend(pid) kills the whole backend. The victim sees:

FATAL:  terminating connection due to administrator command
server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.
connection to server was lost

The trap is that pg_cancel_backend returns t whether or not there was anything to cancel. Against an idle in transaction session it reports success and changes nothing:

SELECT pg_cancel_backend(72472);   -- t
SELECT pid, state FROM pg_stat_activity WHERE pid = 72472;

  pid  |        state
-------+---------------------
 72472 | idle in transaction

SELECT pg_terminate_backend(72472);   -- t  (session is gone)

A session holding locks with no statement running is the usual reason a table will not ALTER, and cancel is the wrong tool for it. Both functions return f plus a WARNING: PID 999999 is not a PostgreSQL backend process for a pid that does not exist, so a t return value is not proof that anything happened.

Non-superusers see blanks, not errors

A role without pg_read_all_stats can read pg_stat_activity, but other users’ rows come back with state, backend_type and wait_event nulled out and query replaced:

 pid  |   usename   | state  |          query           |  backend_type
------+-------------+--------+--------------------------+----------------
 2113 | hw_r6_watch | active | SELECT pid, usename, ... | client backend
 2101 | postgres    |        | <insufficient privilege> |
(2 rows)

Note what that does to the recommended query at the top of this page: because backend_type is null, AND backend_type = 'client backend' filters the masked row out entirely, and the monitoring user sees an empty, reassuring result set. Grant pg_read_all_stats to any role expected to monitor the server: GRANT pg_read_all_stats TO your_role;.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.