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:

Query
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:

Query
SET ROLE doc_reporter;

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

Query
SELECT current_user, current_role, session_user;
Result
 current_user | current_role | session_user--------------+--------------+-------------- doc_reporter | doc_reporter | postgres

Access checks are made against the current role:

Query
SELECT id FROM doc_report;
Result
 id----  1

Switch back:

Query
RESET ROLE;
Query
SHOW role;
Result
 role------ none

Setting a role that does not exist is an error:

Query
SET ROLE doc_no_such_role;
Result
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

This page contains: