CURRENT_USER returns the name of the role executing the current SQL statement.
Call CURRENT_USER
anywhere in a query to obtain the session’s role name. No arguments are required, and the value is constant for the duration of the statement.
Use SELECT CURRENT_USER;
in psql or embed the function inside larger queries, joins, or expressions. Alias it when needed for readability.
Create an created_by
column and set its default to CURRENT_USER
. Every new row then stores the login that executed the INSERT
.
```sqlALTER TABLE Orders ADD COLUMN created_by text DEFAULT CURRENT_USER;```
Yes. Mix it with regular columns to record both business and audit data in the same statement.
```sqlINSERT INTO Orders (id, customer_id, order_date, total_amount, created_by)SELECT o.id, o.customer_id, NOW(), 99.95, CURRENT_USERFROM temp_new_orders o;```
Store the value in lowercase for consistent joins. Always grant roles instead of individual users so audit data remains stable after staff changes.
Mixing CURRENT_USER with SET ROLE. After SET ROLE
, CURRENT_USER
keeps the original login role; use SESSION_USER
if you need the pre-SET ROLE
name.
Using CURRENT_USER in PL/pgSQL triggers without qualification. Inside a security-definer function, CURRENT_USER
returns the definer, not the caller. Use current_setting('role')
or SESSION_USER
if you need the invoker.
No. Every logged-in role can call the function without additional grants.
Yes. PostgreSQL treats USER
and CURRENT_USER
as synonyms.
Yes, e.g., (CURRENT_USER)::text
to make the type explicit.