MySQL Delete Database

Table of Contents

Introduction

The DROP DATABASE command is a basic command of the MySQL language and is used to delete an existing database.
Please pay attention to this command because by deleting a database you will also delete all the tables and therefore also your data.

Preliminary operations

Before to start it is important that you have MySQL installed on your computer.
If you have not installed it yet, you can download it and follow the instructions to install it.

Delete Database in MySQL

First, let’s see the syntax of the DROP DATABASE command in MySQL.

DROP DATABASE [IF EXISTS] <DB_name>;

As you can see, there is the possibility to use the optional parameter if exists. This allows us not to get errors in case the database we are trying to delete does not exist.

How to delete a database in MySQL

Since we want to delete an existing MySQL database, my suggestion is to create a new database and then delete it.
In this way we will avoid deleting existing tables and data and losing useful information.

To learn how to create a database in MySQL check out this post.

Let’s assume we have created a database which is called db_to_delete.
The output of the SHOW DATABASES command is as follows.

SHOW DATABASES command output after db creation
SHOW DATABASES command output after db creation

As you can see the database exists and now we are going to delete it with the following command.

DROP DATABASE db_to_delete;

We repeat the SHOW DATABASES command:

SHOW DATABASES command output after database deletion
SHOW DATABASES command output after database deletion

As you can see, the database has been successfully deleted.

How to delete a database that does not exist in MySQL

Suppose we want to delete a MySQL database without knowing if it exists or not.
Usually if you try to delete a database that doesn’t exist you will get an error like this:

Can't drop database '<db_name>'; database doesn't exist

However, there is a very simple way to avoid this unfortunate error.
Just add the IF EXISTS option before the database name to avoid the error.

DROP DATABASE IF EXISTS <db_name>;

This option is very convenient but it kind of hides errors. Always be careful what you erase and what commands you launch.

Conclusion

Here we are at the end of this post!
I hope now you know how best to use DROP DATABASE command in MySQL.
If you have any doubts, don’t hesitate to write a comment below!

Last but not least, I invite you to continue learning by reading a few more posts!

Leave a Comment

Your email address will not be published. Required fields are marked *