[sql] How can you get the active users connected to a postgreSQL database via SQL?

How can you get the active users connected to a postgreSQL database via SQL? This could be the userid's or number of users.

This question is related to sql postgresql active-users

The answer is


Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;