Skip to content
Advertisement

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

Which of the following two is more accurate?

select numbackends from pg_stat_database;

select count(*) from pg_stat_activity;

Answer

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.