正确查询以获取 PostgreSQL 数据库中的当前连接数

发布于 2024-10-21 12:30:41 字数 125 浏览 1 评论 0原文

以下两个哪个更准确?

select numbackends from pg_stat_database;

select count(*) from pg_stat_activity;

Which of the following two is more accurate?

select numbackends from pg_stat_database;

select count(*) from pg_stat_activity;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

世态炎凉 2024-10-28 12:30:41

这两个查询并不等同。第一个版本的等效版本是:

SELECT sum(numbackends) FROM pg_stat_database;

在这种情况下,我希望该版本比第二个版本稍快,因为它需要计算的行数较少。但您不太可能能够衡量差异。

两个查询都基于完全相同的数据,因此它们同样准确。

Those two queries 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.

枫以 2024-10-28 12:30:41

以下查询非常有帮助

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;

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;
风蛊 2024-10-28 12:30:41

他们肯定会给出不同的结果。更好的是

select count(*) from pg_stat_activity;

因为它包含与 WAL 发送进程的连接,这些连接被视为常规连接并计入 max_connections

请参阅 max_wal_senders

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

长途伴 2024-10-28 12:30:41

根据状态聚合所有 postgres 会话(有多少处于空闲状态、有多少在做某事...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;

Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;
り繁华旳梦境 2024-10-28 12:30:41

从源代码来看,pg_stat_database 查询似乎为您提供了所有用户与当前数据库的连接数。另一方面,pg_stat_activity 查询仅为查询用户提供当前数据库的连接数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文