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 previlage to create a role using the CREATE ROLE statement. If we accidently 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, primary key(employee_id) );
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;
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.