![]() |
VOOZH | about |
In PostgreSQL, the DROP ROLE statement is used to remove a role from the database. Let us look at the process of dropping a role, including important considerations and steps to ensure smooth execution.
The basic syntax of the DROP ROLE Statement in PostgreSQL is:
DROP ROLE [IF EXISTS] target_role;
Let's analyze the above syntax:
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:
In other words, follow the below statements exactly as shown to drop a role:
REASSIGN OWNED BY target_role TO another_role; DROPOWNED BY target_role; DROPROLE target_role;
Let us take a look at an example of the DROP ROLE Statement in PostgreSQL to better understand the concept.
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.
1. First, log in to PostgreSQL using the Postgres role:
psql -U postgres2. Second, create a new role called 'geeksforgeeks' using the below statement:
CREATE ROLE geeksforgeeks WITH LOGIN PASSWORD 'geeks12345';
3. Third, grant createdb privilege to geeksforgeeks using the below statements:
ALTER ROLE geeksforgeeks CREATEDB;4. 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 salesAdd a new table to the Sales database:
CREATE TABLE employee( employee_id INT GENERATED ALWAYS AS IDENTITY, employee_name VARCHAR(150) NOT NULL, PRIMARY KEY(employee_id) );
Now show the list of tables in the sales database using the below command:
\duThis will show you the following result:
👁 PostgreSQL DROP ROLE ExampleNow log in as Postgres and attempt to drop the geeksforgeeks role:
DROP ROLE geeksforgeeks;Output:
👁 PostgreSQL DROP ROLE Example
- Use the
IF EXISTSclause to avoid errors when running scripts that may try to drop non-existent roles.- Only a superuser can drop another superuser role. To drop a non-superuser role, you need the
CREATE ROLEprivilege.- Use the
REASSIGN OWNEDstatement to transfer ownership of database objects to another role.- Before dropping a role, ensure that all permissions granted to the role are revoked.