DROP TABLE IF EXISTS in SQLite

In SQLite, 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.

When I ran the statement again (after it had already been dropped), I didn’t get an error.

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

DROP TABLE t1;

Result:

Error: no such table: t1

This time we get an error telling us that the table doesn’t exist.

See SQLite DROP TABLE for a discussion on foreign keys and view dependencies when dropping tables in SQLite.

You can also run a query against the sqlite_master table if you just want to check if a table exists without dropping it.