Count connections by state, database and user in PostgreSQL
A short GROUP BY over pg_stat_activity answers the first connection questions: how many sessions, from which database and user, doing what.
The task
Connection debugging starts with distribution, not detail. Grouping pg_stat_activity by state shows how many sessions are active, idle, or idle in transaction; grouped by database and user, the same rows show which application holds the connections. Start here before looking at individual pids.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT backend_type, state, COUNT(*) AS sessions
FROM pg_stat_activity
GROUP BY backend_type, state
ORDER BY sessions DESC;
Como funciona
pg_stat_activity has one row per server process, background processes included, so the query groups by backend_type as well; client connections are 'client backend'. For those, state is active while a statement runs, idle between statements, and idle in transaction inside an open transaction that is not running anything. Background processes such as the checkpointer and autovacuum launcher have a NULL state. A large idle count usually means a generously sized connection pool and is harmless; a growing idle in transaction count is not. Ordinary roles can use max_connections minus superuser_reserved_connections (and minus reserved_connections on PostgreSQL 16 and later), so applications hit the limit before the count reaches max_connections.
Variations
Break down by database, user and lock waits
SELECT datname, usename, state,
COUNT(*) AS sessions,
COUNT(*) FILTER (WHERE wait_event_type = 'Lock') AS waiting_on_locks,
COUNT(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_txn
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY datname, usename, state
ORDER BY datname, sessions DESC;
SQL Server: sessions grouped by status
SQL ServerSELECT s.status, COUNT(*) AS sessions
FROM sys.dm_exec_sessions s
WHERE s.is_user_process = 1
GROUP BY s.status
ORDER BY sessions DESC;
Questions that come up
What is a healthy state distribution?
For a pooled OLTP application: mostly idle (the pool keeping connections ready), an active count around the number of CPU cores or below, and close to zero idle in transaction. Active sessions far above the core count mean they are queueing for CPU or locks, and a transaction-mode pooler such as PgBouncer in front of the database usually helps more than more connections.
Why do background sessions show state NULL?
The checkpointer, WAL writer, autovacuum launcher and similar internal processes have no client session, so state is NULL. Add WHERE backend_type = 'client backend' when you only care about application connections, as the variant does.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.