totn PostgreSQL

PostgreSQL: Find Users logged into PostgreSQL

Question:Is there a query to run that will return all Users that are currently logged into PostgreSQL?

Answer: In PostgreSQL, there is a system view called pg_stat_activity which shows the current processes being run in the database. You can run a query against this system view that returns all of the Users that are currently have a process running in the PostgreSQL database.

To retrieve all Users logged into PostgreSQL, you can execute the following SQL statement:

SELECT DISTINCT usename
FROM pg_stat_activity;

This SELECT statement will return the users that are currently running a process in PostgreSQL.

TIP: You must have superuser privileges to see processes owned by other users. Otherwise, you will only see your own processes.

The pg_stat_activity view contains the following columns:

Column Explanation
datid Database ID where process is running
datname Database name where process is running
pid Process ID
usesysid User ID (number assigned by PostgreSQL)
usename User name (ie: postgres, techonthenet, etc)
application_name Application name
client_addr Client's address
client_hostname Client's hostname
client_port Client's port number
backend_start  
xact_start  
query_start Time when query was started
state_change Time when the query's state was changed
waiting Boolean value indicating query's waiting status (t or f)
state State of query (ie: idle, active)
query Current query