DROP TABLE IF EXISTS in MySQL

In MySQL, we can use the IF EXISTS clause of the DROP TABLE statement to check whether the table exists or not before dropping it.

Example

Here’s an example to demonstrate:

DROP TABLE IF EXISTS t1;

That statement drops a table called t1 if it exists.

When I ran that statement, the table already existed, and so it was dropped and I got the following message:

Query OK, 0 rows affected (0.00 sec)

When I ran the statement again (after it had already been dropped), I got the following message:

Query OK, 0 rows affected, 1 warning (0.00 sec)

So there was no error, but I did get a warning.

Let’s take a look at the warning:

SHOW WARNINGS;

Result:

+-------+------+-------------------------+
| Level | Code | Message                 |
+-------+------+-------------------------+
| Note  | 1051 | Unknown table 'test.t1' |
+-------+------+-------------------------+

The warning tells us that the table doesn’t exist, but it’s not an error.

Here’s what happens when we don’t use IF EXISTS:

DROP TABLE t1;

Result:

ERROR 1051 (42S02): Unknown table 'test.t1'

This time we get an error.

Also see 5 Ways to Check if a Table Exists in MySQL if you just want to check if a table exists without dropping it.