Skip to main content

SET ROLE

The SET ROLE statement switches the current role of the session. Privilege checks then apply to that role instead of the role you authenticated as. A superuser can set any role; other users can only set roles they are a member of. RESET ROLE (or SET ROLE DEFAULT) switches back.

Examples​

Given a role with access to a table:

SQL
CREATE ROLE doc_reporter;
CREATE TABLE doc_report (id int);
INSERT INTO doc_report VALUES (1);
GRANT SELECT ON doc_report TO doc_reporter;

Switch to it:

SQL
SET ROLE doc_reporter;

current_user and current_role now report the set role, while session_user remains the role that authenticated:

SQL
SELECT current_user, current_role, session_user;
 current_user | current_role | session_user
--------------+--------------+--------------
 doc_reporter | doc_reporter | postgres

Access checks are made against the current role:

SQL
SELECT id FROM doc_report;
 id
----
  1

Switch back:

SQL
RESET ROLE;
SQL
SHOW role;
 role
------
 none

Setting a role that does not exist is an error:

SQL
SET ROLE doc_no_such_role;
error db error: ERROR: role "doc_no_such_role" does not exist

Notes​

  • Setting a role you are not a member of fails with permission denied to set role "..." (superusers are exempt).
  • The switch lasts for the session (until RESET ROLE, another SET ROLE, or disconnect).

See also​

Syntax​

Syntax