In PostgreSQL the DROP ROLE statement to remove a role.
Syntax: DROP ROLE [IF EXISTS] target_role;
Let’s analyze the above syntax:
- After the DROP ROLE keywords add the role name that is to be deleted.
- Use the IF EXISTS option can be used to issue a notice instead of an error when a request to remove a role that does not exist is made.
it is important to note that to remove a superuser role, one needs to be a superuser. To remove a non-superuser roles, you will need the privilege to create a role using the CREATE ROLE statement. If we accidentally try to remove a role that has been referenced in any database, PostgreSQL raises an error. In this case, one has to take two steps:
- You either need to remove the database objects owned by that particular role using the DROP OWNED statement or reassign the ownership of the database objects to another role using the REASSIGN OWNED statement.
- You will also be needing to revoke all other permissions granted to the role.
In other words, follow the below statements exactly as shown to drop a role:
REASSIGN OWNED BY target_role TO another_role;
DROP OWNED BY target_role;
DROP ROLE target_role;
In this example:
- Here, we will create a new role called geeksforgeeks and use this role to create a table named employees.
- Then, we will show the step by step guide on how to remove the role geeksforgeeks from the PostgreSQL database server.
First, log in to PostgreSQL using the Postgres role:
psql -U postgres
Second, create a new role called geeksforgeeks using the below statement:
create role geeksforgeeks with login password 'geeks12345';
Third, grant createdb privilege to geeksforgeeks using the below statements:
alter role geeksforgeeks createdb;
Fourth, create a new database called sales:
create database sales;
Now, login to the PostgreSQL database server using the geeksforgeeks role as shown below:
psql -U geeksforgeeks -W sales
Add a new table to the Sales database:
create table employee(
customer_id int generated always as identity,
customer_name varchar(150) not null,
Now show the list of tables in the sales database using the below command:
This will show you the following result:
Now log in as Postgres and attempt to drop the geeksforgeeks role:
drop role geeksforgeeks;
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!