Skip to content

Instantly share code, notes, and snippets.

@mekarpeles
Created January 3, 2025 21:47
Show Gist options
  • Save mekarpeles/672e97912c8cdbffc753124b325ba563 to your computer and use it in GitHub Desktop.
Save mekarpeles/672e97912c8cdbffc753124b325ba563 to your computer and use it in GitHub Desktop.
Psql Check Connections Recipe
WITH connection_stats AS (
SELECT
state,
COUNT(*) AS count
FROM
pg_stat_activity
GROUP BY
state
),
total_connections AS (
SELECT
COUNT(*) AS total_conn
FROM
pg_stat_activity
)
SELECT
tc.total_conn,
(SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_conn,
((SELECT setting::int FROM pg_settings WHERE name = 'max_connections') - tc.total_conn) AS available_conn,
COALESCE(cs.count, 0) AS active,
COALESCE((SELECT count FROM connection_stats WHERE state = 'idle in transaction'), 0) AS idle_in_transaction,
COALESCE((SELECT count FROM connection_stats WHERE state = 'idle'), 0) AS idle
FROM
total_connections tc
LEFT JOIN
connection_stats cs ON cs.state = 'active';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment