Summarize PostgreSQL sessions by state
Build a paste-ready command, then review its compatibility and effects before running it.
psql -d <database> -c "select state, count(*) from pg_stat_activity group by state order by state;"Complete required fields to copy the generated command.
Compatibility
LinuxVerified for Linux using posix, bash, zsh syntax.
Operational knowledgereview due 2027-01-20
Requirementspsqlpsql must be installed and available on PATH.Network accessThe target must be reachable from the current environment.
Version supportpsql Current supported releasesVerified for linux using posix, bash, zsh syntax; consult compatibility notes for platform-specific differences.
Expected signalsstate | countRepresentative successful output; values vary with the selected target and system state.
Known errorspsql: command not foundpsql is missing or is not available on PATH.
Verifypsql -d {{database}} -c "select state, count(*) from pg_stat_activity group by state order by state;"The output matches the expected target and exits without an error.Rollback noteNot required: this command is read-only and does not change system state.
Command breakdown
01psqlCommandRuns the psql stage of this one-liner.
02-dOptionConfigures psql with the -d option.
03<database>ParameterA value supplied in the Fill parameters section.
04-cOptionConfigures psql with the -c option.
05"select state, count(*) from pg_stat_activity group by state order by state;"ArgumentPasses "select state, count(*) from pg_stat_activity group by state order by state;" to psql.
Example input
psql -d appdb -c "select state, count(*) from pg_stat_activity group by state order by state;"
Example output
state | count
--------+-------
active | 3
idle | 18
(2 rows)
Illustrative output — exact values vary by system and data.
Official sources