DROP TABLE IF EXISTS in MariaDB

In MariaDB, 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.156 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.028 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 'zap.t1' |
+-------+------+------------------------+

So the warning tells us that the table doesn’t exist, but at least 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 'zap.t1'

This time we get an error.

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