Sub topic 10
Making scripts re-runnable with IF EXISTS
This chapter assumes you can write CREATE TABLE, ALTER TABLE ... ADD COLUMN and DROP TABLE, and that you know what a foreign key does. The examples use PostgreSQL unless a heading says otherwise. You can follow them in any test database, but the dialect section shows where other systems differ.
The problem: scripts that fail on the second run
A schema script is often run more than once. You run it on your laptop, then on a staging server, and again after fixing a typo. The first run works. The second fails:
DROP TABLE orders;
-- ERROR: table "orders" does not existMany tools stop at the first error, so one failed DROP can block the whole script. A script that gives the same end state however many times you run it is called idempotent. IF EXISTS is the main tool for making DROP statements idempotent. Its counterpart IF NOT EXISTS does the same for statements that create things.
DROP TABLE IF EXISTS
Adding IF EXISTS turns "the table is missing" from an error into a no-op:
DROP TABLE IF EXISTS orders;If orders exists, it is dropped. If it does not, the statement succeeds and does nothing. Most databases still report that nothing happened. PostgreSQL raises a NOTICE ("table "orders" does not exist, skipping"). MySQL records a warning that you can read with SHOW WARNINGS. Neither stops the script.
You can name several tables in one statement:
DROP TABLE IF EXISTS order_items, orders, customers;In PostgreSQL and MySQL, each missing table is skipped and the others are dropped. List child tables before parent tables so foreign keys do not block the drop. The next chapters cover dependencies in detail.
IF EXISTS on ALTER TABLE
Support differs by database. PostgreSQL accepts IF EXISTS in several places inside ALTER TABLE:
-- Skip the whole statement if the table is missing
ALTER TABLE IF EXISTS customers ADD COLUMN phone VARCHAR(30);
-- Skip only if the column is missing
ALTER TABLE customers DROP COLUMN IF EXISTS phone;
-- Skip only if the constraint is missing
ALTER TABLE orders DROP CONSTRAINT IF EXISTS fk_orders_customer;The first form guards the table. The other two guard an object inside a table that must exist. If customers is missing, DROP COLUMN IF EXISTS still fails, because the table itself is not found. Use ALTER TABLE IF EXISTS as well when the table may be absent.
IF NOT EXISTS: the other direction
Adding things has the opposite problem. A second run of ADD COLUMN fails because the column already exists. PostgreSQL provides:
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
ALTER TABLE customers ADD COLUMN IF NOT EXISTS email VARCHAR(255);A full re-runnable script combines both forms. This one can run any number of times against PostgreSQL:
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
ALTER TABLE customers ADD COLUMN IF NOT EXISTS email VARCHAR(255);
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
);Note the pattern. orders is dropped and recreated, so it always ends up in the same state. customers is kept, because it may hold data, and is only brought up to date.
How the decision works
IF EXISTS only answers the first question: does the object exist? It does not bypass the second one. If customers exists and orders references it, this still fails in PostgreSQL:
DROP TABLE IF EXISTS customers;
-- ERROR: cannot drop table customers because other objects depend on itDialect support
| Statement | PostgreSQL | MySQL | SQL Server 2016+ | SQLite |
|---|---|---|---|---|
| `DROP TABLE IF EXISTS` | Yes | Yes | Yes | Yes |
| `CREATE TABLE IF NOT EXISTS` | Yes | Yes | No | Yes |
| `ALTER TABLE IF EXISTS` | Yes | No | No | No |
| `ADD COLUMN IF NOT EXISTS` | Yes | No (MariaDB only) | No | No |
| `DROP COLUMN IF EXISTS` | Yes | No (MariaDB only) | Yes | No |
| `DROP CONSTRAINT IF EXISTS` | Yes | No | Yes | No |
Oracle added DROP TABLE IF EXISTS only in version 23ai. Check your version's documentation before relying on any cell in this table.
Where the syntax is missing, check the catalog yourself. In SQL Server, for example, you can test for a column before adding it:
IF COL_LENGTH('dbo.customers', 'email') IS NULL
ALTER TABLE dbo.customers ADD email VARCHAR(255);In MySQL, you would query information_schema.columns for the table and column, and run the ALTER only when no row comes back. MySQL does not allow a bare IF statement outside stored programs, so this is normally done in a stored procedure or in your migration tool.
Pitfalls
Typos are silent
DROP TABLE IF EXISTS cutomers; succeeds and drops nothing. In a plain DROP TABLE, the same typo would have raised an error. Review notices and warnings, especially in automated runs. Do not use IF EXISTS on every statement by habit. Use it where "already gone" is a legitimate state.
The name may refer to something else
IF EXISTS checks only the name. It does not check that the table has the shape you expect. If another schema or an older version of the table has that name, the statement acts on it. Qualify names (public.orders) when more than one schema is in play. PostgreSQL resolves unqualified names through the search_path, so the same script can touch different tables for different users.
Re-runnable is not the same as safe
DROP TABLE IF EXISTS orders is repeatable, but each run destroys the data in orders. A script that recreates a table on every run is fine for a test database and dangerous against production. For tables holding real data, prefer the IF NOT EXISTS forms, which keep existing rows.
A skipped statement hides drift
If ADD COLUMN IF NOT EXISTS status VARCHAR(20) finds an existing status column of a different type, it does nothing and reports no error. The database now differs from what your script describes. Idempotent scripts handle "already done" but not "done differently".
Transactions and partial runs
In PostgreSQL, you can wrap a re-runnable script in BEGIN ... COMMIT so a failure leaves nothing half-applied. In MySQL, DDL commits implicitly, so a script that fails midway leaves earlier changes in place. Re-runnable statements are what let you simply run the script again to finish the job.
Exercises
Exercise
A PostgreSQL script runs DROP TABLE IF EXISTS customers; while the table orders has a foreign key pointing to customers. Does the statement succeed? What would you change to make it succeed, and what is the cost?
Show answer
It fails with a dependency error, because customers exists and IF EXISTS only skips the statement when the table is missing. You can drop orders first (DROP TABLE IF EXISTS orders, customers; or two statements in that order). Or you can use DROP TABLE IF EXISTS customers CASCADE;, which removes the foreign key constraint but leaves orders in place without it. The cost of the first is losing the orders data. The cost of the second is silently losing the foreign key's integrity check.
Exercise
You must add an email column to customers on SQL Server, and the script may run several times. Write a statement that is safe to re-run.
Show answer
IF COLLENGTH('dbo.customers', 'email') IS NULL
ALTER TABLE dbo.customers ADD email VARCHAR(255);
The `COLLENGTH function returns NULL when the column does not exist, so the ALTER runs only on the first execution. SQL Server has no ADD COLUMN IF NOT EXISTS, and its ADD clause omits the COLUMN` keyword.