Learn how to use DROP ROLE command to remove users and roles in PostgreSQL. Includes ownership rules, REASSIGN OWNED BY syntax, and safe role deletion methods.
In PostgreSQL, DROP ROLE is used to remove (delete) a role/user from the system.
DROP ROLE?π It is a command used to:
DROP ROLE?DROP ROLE role_name;
CREATE ROLE test_user WITH LOGIN PASSWORD '123';
DROP ROLE test_user;
βοΈ The role is now removed from PostgreSQL
You CANNOT drop a role if it:
Example:
ALTER DATABASE dvdrental OWNER TO test_user;
Then:
DROP ROLE test_user; -- β ERROR
REASSIGN OWNED BY test_user TO postgres;
DROP OWNED BY test_user;
DROP ROLE test_user;
-- Create role
CREATE ROLE trainee WITH LOGIN PASSWORD '123';
-- Give access
GRANT CONNECT ON DATABASE dvdrental TO trainee;
-- Remove role safely
REASSIGN OWNED BY trainee TO postgres;
DROP OWNED BY trainee;
DROP ROLE trainee;
π A role cannot be deleted if it is still linked to database objects
Ask students: π βWhy did DROP ROLE fail?β
This helps them understand:
SELECT rolname FROM pg_roles;
DROP ROLE in PostgreSQLStudents will learn:
DROP ROLE may failYou are managing a system where temporary users (trainees, interns, students) must be removed after use.
CREATE ROLE trainee WITH LOGIN PASSWORD '123';
Verify:
SELECT rolname FROM pg_roles;
```sql id=βmqy8mxβ DROP ROLE trainee;
βοΈ Works because:
* No ownership
* No permissions
* No dependencies
---
### πΉ Step 3: Create Role Again
```sql
CREATE ROLE trainee WITH LOGIN PASSWORD '123';
GRANT CONNECT ON DATABASE dvdrental TO trainee;
Try dropping:
```sql id=βyxczgiβ DROP ROLE trainee;
π β Ask students:
* Does it work or fail?
βοΈ Usually it **fails** due to dependencies
---
# πΉ Step 5: Fix the Error
```sql
DROP OWNED BY trainee;
DROP ROLE trainee;
CREATE ROLE trainee WITH LOGIN PASSWORD '123';
ALTER DATABASE dvdrental OWNER TO trainee;
Now try:
DROP ROLE trainee;
β This will FAIL
π Because:
REASSIGN OWNED BY trainee TO postgres;
Then:
DROP OWNED BY trainee;
βRemove everything that this role (trainee) owns in the current database.β
This includes:
Finally:
DROP ROLE trainee;
βοΈ Now it works
SELECT datname, pg_catalog.pg_get_userbyid(datdba) AS owner
FROM pg_database;
temp_userinternmanagerREASSIGN OWNEDALTER TABLE film OWNER TO trainee;
Try:
DROP ROLE trainee;
π Fix it properly
| Concept | Explanation |
|---|---|
| DROP ROLE | Deletes a user/role |
| Dependency | Role linked to objects |
| REASSIGN OWNED | Transfer ownership |
| DROP OWNED | Remove permissions |
| Ownership | Strongest control |
| Error | Reason |
|---|---|
| cannot drop role | still owns objects |
| permission denied | not superuser |
| role is in use | active connections |