SQL Drop Database
The DROP DATABASE statement removes an entire database from a database server.
This is a destructive command. When a database is dropped, its tables, views, stored objects and stored data are removed with it. In most real systems, you should only run this command after confirming the target environment and creating a backup.
Basic Syntax
The basic syntax is:
DROP DATABASE database_name;
The database name should be the name of the database you want to remove.
Example
The following command drops a database named test_store:
DROP DATABASE test_store;
After the command is executed successfully, the test_store database is no longer available.
Using IF EXISTS
Many database systems support IF EXISTS to avoid an error when the database does not exist:
DROP DATABASE IF EXISTS test_store;
This form is useful in scripts because the command can continue even if test_store has already been removed.
Before Dropping a Database
Before using DROP DATABASE, check the following points:
- Make sure you are connected to the correct server and environment.
- Confirm that the database name is exactly the database you want to remove.
- Create and test a backup if the data may be needed later.
- Check whether other users, applications or scheduled jobs are using the database.
- Make sure your account has permission to drop the database.
Database System Notes
The general idea is the same across SQL databases, but details can vary by system.
| Database system | Notes |
|---|---|
| MySQL and MariaDB | DROP DATABASE database_name; removes the database and its tables. IF EXISTS is commonly supported. |
| PostgreSQL | You cannot drop the database you are currently connected to. The command is usually run while connected to another database. |
| SQL Server | The database must not be in use by your current connection. Active connections may need to be closed before the database can be dropped. |
| Oracle | Oracle database removal is an administrative operation and is not usually taught as a regular table-level SQL command. |
DROP DATABASE vs Other Delete Commands
| Command | What it removes |
|---|---|
DELETE |
Rows from a table. |
TRUNCATE TABLE |
All rows from a table, while keeping the table structure. |
DROP TABLE |
One table and its data. |
DROP DATABASE |
The entire database and the objects inside it. |
Common Mistakes
- Running the command in production when it was intended for a test database.
- Confusing
DROP DATABASEwithDROP TABLE. - Assuming the operation can be undone without a backup.
- Using a vague database name in scripts without checking the target server first.