Explain Codes LogoExplain Codes Logo

Right query to get the current number of connections in a PostgreSQL DB

sql
postgresql
database
connections
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

For a quick assessment of the connections to your PostgreSQL database, run this query:

SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database(); -- Count? Count Dracula? Is that you?

This immediately counts all the current connections to the particular database you're linked to.

Essential queries and configurations

  • Targeted pg_stat_activity query: Great for a detailed snapshot.
  • Summarized pg_stat_database query: Swift count across all databases.
  • max_connections: The limit of simultaneous connections.
  • superuser_reserved_connections: A set number of connections reserved for superusers.
  • Replication mechanisms: The role of max_wal_senders in connection count.

Summarized count for quick view

If the goal is retrieving a summary of connections, you'd use:

SELECT sum(numbackends) FROM pg_stat_database; -- SQL: The backend story.

Though bearing fewer rows to process, it provides a summary, lacking in insight into the specific connection states.

Deep dive: Group by state

For a richer understanding of connection states, incorporate pg_stat_activity with groupings:

SELECT state, COUNT(*) FROM pg_stat_activity GROUP BY state; -- Like a SQL "sorting hat"!

This displays connections grouped according to their current state, providing a more nuanced picture of the ongoing database activity.

Configurations impacting connection count

Remember, PostgreSQL configurations play a central role in controlling and understanding connections:

  • max_connections: This is your capacity, your database’s version of "maximum occupancy".
  • superuser_reserved_connections: These are your VIP seats, reserved for the superusers.
  • max_wal_senders: This is the behind-the-scenes crew, responsible for replication connections apart from client activity.

Performance nuances

In a high-performance environment, opt for the summarized pg_stat_database view for faster results. But keep in mind, for a regular-functioning database, the performance delta between detailed and summarized views is bearly noticeable.