How to check whether a user is connected to PostgreSQL or not

In this article, we will see how to check whether a user is connected or not to PostgreSQL server. We can get this information from the system view pg_stat_activity.

Check whether user ‘james’ is connected to PostgreSQL or not

select datname from pg_stat_activity where usename='james';

Output:

datname ----------- r2schools (1 row)

So user ‘james’ connected to PostgreSQL Server and working on database ‘r2schools’.

Check whether user ‘george’ is connected to PostgreSQL or not

select datname from pg_stat_activity where usename='george';

Output:

datname ----------- (0 rows)

Which means the user george not connected to the PostgreSQL server.
How to check whether a user is connected to PostgreSQL or not