Created
January 3, 2025 21:47
-
-
Save mekarpeles/672e97912c8cdbffc753124b325ba563 to your computer and use it in GitHub Desktop.
Psql Check Connections Recipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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