How to Drop Database in PostgreSQL: Syntax and Examples
To drop a database in PostgreSQL, use the
DROP DATABASE database_name; command. You must connect to a different database (not the one you want to drop) and have the necessary privileges to execute this command.Syntax
The basic syntax to drop a database in PostgreSQL is:
DROP DATABASE database_name;- deletes the specified database permanently.- You cannot drop the database you are currently connected to.
- You need to be a superuser or the owner of the database.
sql
DROP DATABASE database_name;Example
This example shows how to drop a database named testdb. First, connect to the default postgres database, then run the drop command.
sql
\c postgres
DROP DATABASE testdb;Output
You are now connected to database "postgres".
DROP DATABASE
Common Pitfalls
Common mistakes when dropping a database include:
- Trying to drop the database while connected to it, which causes an error.
- Not having sufficient privileges to drop the database.
- Accidentally dropping the wrong database without backup.
Always connect to a different database before dropping.
sql
/* Wrong: connected to the database you want to drop */ \c testdb DROP DATABASE testdb; /* Right: connect to another database first */ \c postgres DROP DATABASE testdb;
Output
ERROR: cannot drop the currently open database
You are now connected to database "postgres".
DROP DATABASE
Quick Reference
| Command | Description |
|---|---|
| DROP DATABASE database_name; | Deletes the specified database permanently. |
| \c database_name | Connects to a specified database. |
| \c postgres | Connects to the default maintenance database. |
| Cannot drop current database | You must connect to a different database before dropping. |
Key Takeaways
Use
DROP DATABASE database_name; to delete a database in PostgreSQL.You must connect to a different database before dropping the target database.
Ensure you have the required privileges to drop the database.
Dropping a database is irreversible; always double-check before running the command.
Common error: trying to drop the database you are currently connected to.