PotgreSQL: How to display PostgreSQL Server sessions

You can display the active sessions (connections) on a PostgreSQL server by querying the pg_stat_activity view. This view provides information about the currently active connections and their associated queries. Here’s how you can use it:

  1. Connect to PostgreSQL: Start by connecting to your PostgreSQL server using the psql command-line client or another PostgreSQL client of your choice. You may need to provide the appropriate username and password or other authentication details.bashCopy codepsql -U your_username -d your_database_name
  2. Query pg_stat_activity: Once connected, you can query the pg_stat_activity view to see the active sessions. You can run the following SQL query: SELECT * FROM pg_stat_activity; This query will return a list of all active sessions, including information such as the process ID (pid), username (usename), database (datname), client address (client_addr), and the SQL query being executed (query). The state column provides the current state of each session, which can be helpful for diagnosing issues.
  3. Filter and Format the Output: If you want to filter the results or display specific columns, you can modify the query accordingly. For example, to see only the username, database, and query being executed, you can use the following query:SELECT usename, datname, query FROM pg_stat_activity; You can also use WHERE clauses to filter the results based on specific criteria. For instance, to see only sessions with a specific application name, you can do: SELECT * FROM pg_stat_activity WHERE application_name = 'your_application_name';
  4. Exit psql: After viewing the active sessions, you can exit the PostgreSQL client by typing: \q

This will return you to the command line.

Keep in mind that pg_stat_activity provides a snapshot of active sessions at the time you run the query. If you want to continuously monitor sessions in real-time, you may want to use monitoring tools or automate queries to periodically check the pg_stat_activity view.

Leave a comment