Skip to content

IF EXISTS … THEN

Runs one statement only if a query returns at least one row, or with NOT, only if it returns none.

LibRed extension. ACE has no such statement. The Jet provider (EFCore.Jet) accepts the same text, but it never reaches ACE: the provider’s command runs the query itself, then sends ACE only the statement after THEN, or nothing.

IF [ NOT ] EXISTS ( query_expression ) THEN statement

Run statement only if query_expression returns no rows.

Any query. Only whether it returns a row matters, not what it returns. It is often a query over `INFORMATION_SCHEMA.TABLES` or `INFORMATION_SCHEMA.COLUMNS`, to test whether a table or column exists.

The one statement to run: CREATE TABLE, CREATE INDEX, CREATE VIEW, CREATE PROCEDURE, ALTER TABLE, DROP, INSERT, UPDATE, DELETE, EXECUTE or a SELECT. A SELECT, or a procedure that selects, returns its rows when it runs.

A transaction statement or another IF is not accepted here.

This is what EF Core emits for idempotent migration scripts, and LibRed’s EF Core provider uses it to create the migrations history table only when it is missing. It makes a script safe to run twice: the second run skips what the first one did.

When the guard holds, the statement behaves exactly as it would on its own, and the command reports its row count. When the guard skips the statement, the command reports 0 rows.

The names INFORMATION_SCHEMA.TABLES and INFORMATION_SCHEMA.COLUMNS contain a dot, so write each in backticks as one name.

These run against the Northwind sample database, as in the playground. They follow on from each other, and each can be run again with no error.

Create a table only if it doesn’t exist:

IF NOT EXISTS (SELECT * FROM `INFORMATION_SCHEMA.TABLES` WHERE TABLE_NAME = 'Notes')
THEN CREATE TABLE Notes (Id COUNTER PRIMARY KEY, Body TEXT(255))

Add a column only if it doesn’t exist:

IF NOT EXISTS (SELECT * FROM `INFORMATION_SCHEMA.COLUMNS`
WHERE TABLE_NAME = 'Notes' AND COLUMN_NAME = 'Author')
THEN ALTER TABLE Notes ADD COLUMN Author TEXT(50)

Insert a row only if a query finds something:

IF EXISTS (SELECT * FROM Customers WHERE Country = 'Norway')
THEN INSERT INTO Notes (Body) VALUES ('We have Norwegian customers')