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

我是研究僧i 提交于 2019-12-18 09:59:34

问题


Which of the following two is more accurate?

select numbackends from pg_stat_database;

select count(*) from pg_stat_activity;

回答1:


Those two requires aren't equivalent. The equivalent version of the first one would be:

SELECT sum(numbackends) FROM pg_stat_database;

In that case, I would expect that version to be slightly faster than the second one, simply because it has fewer rows to count. But you are not likely going to be able to measure a difference.

Both queries are based on exactly the same data, so they will be equally accurate.




回答2:


The following query is very helpful

select  * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;



回答3:


They definitely may give different results. The better one is

select count(*) from pg_stat_activity;

It's because it includes connections to WAL sender processes which are treated as regular connections and count towards max_connections.

See max_wal_senders




回答4:


Number of TCP connections will help you. Remember that it is not for a particular database

netstat -a -n | find /c "127.0.0.1:13306"



回答5:


From looking at the source code, it seems like the pg_stat_database query gives you the number of connections to the current database for all users. On the other hand, the pg_stat_activity query gives the number of connections to the current database for the querying user only.



来源:https://stackoverflow.com/questions/5267715/right-query-to-get-the-current-number-of-connections-in-a-postgresql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!