In PostgreSQL, 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 in Azure Data Studio (with its Postgres extension), the table already existed, and so it was dropped and I got the following message:
Commands completed successfully
When I ran the statement again (after it had already been dropped), I got the following message:
NOTICE: table "t1" does not exist, skipping Commands completed successfully
No error occurred, but I did get a “notice” that the table doesn’t exist, along with a message that the command completed successfully.
Here’s what happens when we don’t use IF EXISTS
:
DROP TABLE t1;
Result:
table "t1" does not exist
This time we get an error telling us that the table doesn’t exist.
Also see 5 Ways to Check if a Table Exists in PostgreSQL if you just want to check whether or not a table exists without dropping it.