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
developersrole 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:
Create a group role for a team of analysts
Grant read-only access to a table
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:
Create a base role for read-only access
Create a manager role that inherits from
read_accessand has additional permissions
Assign a user to the
managerrole
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:
Create a role for a consultant
Assign limited permissions
The consultant role will automatically lose login privileges after December 31, 2024.
Last updated