Introduction
PostgreSQL uses roles to manage access and permissions to databases. A role can be either a user or a group depending on how you set up the role.
The difference between a user and a group is that a user has LOGIN privilege and a group does not.
Groups are mainly used to set privileges for a group of users. If you create a group with certain privileges you can add them to new users. If you change the group's privileges, the privileges for all the users in the group will change as well.
Create Role
Use the following query to create a role:
This will create a role called thomas without LOGIN privilege.
Use the any of the following queries to create a role with LOGIN privilege:
Both will create a role (user) called thomas with LOGIN privilege.
Parameters
CREATE ROLE will accept the following parameters. (The second parameter in the list is the default)
- SUPERUSER or NONSUPERUSER
- CREATEDEB or NOCREATEDB
- CREATEROLE or NOCREATEROLE
- NOINHERIT or INHERIT
- LOGIN or NOLOGIN
- REPLICATION or NOREPLICATION
- CONNECTION LIMIT connlimit - The default is -1 which means unlimited concurrent connections can be made with this role
- PASSWORD password
- VALID UNTIL 'timestamp'
Grant and Revoke
Additional privileges can be granted and revoked to and from roles. These include the following:
- SELECT
- INSERT
- DELETE
- UPDATE
- TRUNCATE
- REFERENCES - to create foreign key contraints
- TRIGGER
- CREATE - to create new schemas or objects in schemas
- CONNECT - allows the role to connect to a specified database
- ALL PRIVILEGES - to grant all privileges
Inheritance
A role can inherit privileges from another role.
Create a role and add some privileges:
Create a second role and grant the first role to the second role:
If you connect to PostgreSQL as bob you will have all the privileged granted to john.
List of available users in a cluster
A list of all available roles in a cluster can be queried from the pg_roles catalog.