More examples on Roles

Roles in PostgreSQL are flexible and can represent different entities: a user, a group, or a permission set.

Let’s look at some examples of how to create and use roles for various scenarios.

1. Basic Role Without Login

A role without the ability to log in can act as a permission set or a group.

Example:

Create a role to manage permissions for application developers.

-- Create a role for developers
CREATE ROLE developers;

-- Grant permissions to the role
GRANT SELECT, INSERT ON employees TO developers;
  • The developers role cannot log in but can have permissions assigned.

  • Individual users (like Alice and Bob) can be added to this role to inherit its permissions.

2. Role with Login (User Role)

A role that can log in is considered a user.

Example:

Create a user role for an individual database user.

Alice can now log in to the database and has SELECT access to the employees table.

3. Role as a Group

A role can act as a group to simplify permission management for multiple users.

Example:

  1. Create a group role for a team of analysts

  1. Grant read-only access to a table

  1. Add individual users to the group

Now both Bob and Carol inherit SELECT privileges on the sales_data table from the analysts role.

4. Role with Inheritance

Roles can be nested, meaning one role can inherit permissions from another.

Example:

  1. Create a base role for read-only access

  1. Create a manager role that inherits from read_access and has additional permissions

  1. Assign a user to the manager role

Dave can now perform SELECT, INSERT, and UPDATE operations on the employees table because he inherits read_access through the manager role.

5. Temporary Role for a Consultant

You might need a temporary role for someone who will have limited access for a short time.

Example:

  1. Create a role for a consultant

  1. Assign limited permissions

The consultant role will automatically lose login privileges after December 31, 2024.

Last updated