CURRENT_USER returns the role name executing the current SQL statement.
The CURRENT_USER keyword returns the role name that owns the current SQL session. Its value is fixed at parse time, so it does not change inside the same transaction, even after SET ROLE
.
Audit scripts, debug permission errors, and build security-definer functions by logging or branching on the active role. Knowing who ran a query speeds up compliance checks.
Call it like any scalar expression:
SELECT CURRENT_USER;
You can embed it in SELECT, INSERT, UPDATE, DELETE, views, triggers, and constraints.
INSERT INTO Orders_Audit(order_id, ran_by)
SELECT id, CURRENT_USER
FROM Orders
WHERE order_date >= CURRENT_DATE - INTERVAL '1 day';
Yes. Use an alias for clearer column names:
SELECT CURRENT_USER AS executed_by;
Compare CURRENT_USER
, SESSION_USER
, and USER
to understand role switching. Avoid relying on it inside SECURITY DEFINER functions unless you need the caller’s identity.
No. Every role can read its own name with SELECT CURRENT_USER
.
SESSION_USER shows the role that logged in, while CURRENT_USER shows the role that owns the current statement. They differ only after SET ROLE
.
Yes. For example: CHECK (created_by = CURRENT_USER)
ensures rows are written only by their owners.