In this article, we will look into PostgreSQL group roles and their uses to manage privileges in a PostgreSQL database more effectively. It is a standard practice to create group roles as it can significantly reduce the complexixity and time required to grant or invoke privelages on the database. But there is a catch in this technique. By convention, a group role does not have the LOGIN privilege.
To create a group role, you can use the CREATE ROLE statement as follows:
Syntax: CREATE ROLE group_role_name;
The GRANT statement can be used to add a role to a group role,as shown below: To remove a user role from a group role, you can use the REVOKE statement as shown below: A role can use the privileges of the group role in the following ways: Example: Create a new database called corp: Switch to the corp database: Create the contacts table: Create the forecasts table: Create a role ‘Anil’ that can log in with a password and inherit all privileges of group roles of which it is a member: Grant the select on the forecasts table to Anil: Use the below command to check the grant table: This will lead to the following: Create the marketing group role: Create the planning group role: Grant all privileges on contacts table to marketing: Grant all privileges on forecasts table to planning: Add ‘Anil’ as a member of marketing: Add planning as a member of marketing: Now, the role Anil can select data from the forecasts table: And insert a row into the contacts table: As Anil can insert a row into the forecasts table, PostgreSQL will behave as expected and the insertion will take place as expected. So, check the inserted data use the following command” Output:Syntax: GRANT group_role to user_role;
Syntax: REVOKE group_role FROM user_role;
create database corp;
\c corp
create table contacts(
id int generated always as identity primary key,
name varchar(255) not null,
phone varchar(255) not null
);
create table forecasts(
year int,
month int,
amount numeric
);
create role anil inherit login password 'securePass1';
grant select on forecasts to anil;
\z
create role marketing noinherit;
create role planning noinherit;
grant all on contacts to marketing;
grant all on forecasts to planning;
grant marketing to anil;
grant marketing to planning;
select * from forecasts;
insert into contacts(name, phone) values('Raju kumar', '408-102-3459');
SELECT * FROM contacts;


