PostgreSQL – How to view the Session User

You can use the session_user function to retrieve the name of the user that established the database session.

Here’s how you can use the session_user function in SQL queries:

SELECT session_user;

When you execute this SQL query, it will return the name of the user that established the session. It could be same as currently logged-in user if no other role has been set.

For example, if you are logged in as the user “john,” executing the query will return:

session_user 
------------- 
john 
(1 row)

You can use the session_user function in various scenarios, such as when you need to record the user who made a change to the database or when you want to control access to certain data or functions based on the user’s identity.

Keep in mind that session_user returns the username as a text string, and it is read-only. It cannot be used to change the user’s session state.

Similar Posts