CREATE TABLE IF NOT EXISTS variants
Scripts that create tables should survive being run twice. Most engines have native IF NOT EXISTS; SQL Server needs a small guard block instead.
The task
Bootstrap scripts should behave identically on a fresh database and on one that already has the table, without a manual check before each run.
The snippet
Written for SQLite. Versions for SQL Server, PostgreSQL and MySQL are under Variations.
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY,
key TEXT NOT NULL UNIQUE,
value TEXT
);
Cómo funciona
IF NOT EXISTS makes CREATE TABLE do nothing when the name is taken (MySQL and PostgreSQL report it as a warning or NOTICE), which is what a replayed migration needs. It only checks the name: if a table of that name exists with different columns, the old shape stays and nothing tells you. On SQL Server, OBJECT_ID with type 'U' returns NULL when no user table of that name exists; even SQL Server 2025 rejects CREATE TABLE IF NOT EXISTS as a syntax error.
Variations
SQL Server
SQL ServerIF OBJECT_ID('dbo.Settings', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Settings (
Id INT IDENTITY PRIMARY KEY,
[Key] NVARCHAR(200) NOT NULL UNIQUE,
[Value] NVARCHAR(MAX) NULL
);
END;
PostgreSQL
PostgreSQLCREATE TABLE IF NOT EXISTS settings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
key text NOT NULL UNIQUE,
value text
);
MySQL
MySQLCREATE TABLE IF NOT EXISTS settings (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`key` VARCHAR(200) NOT NULL UNIQUE,
value TEXT
) ENGINE=InnoDB;
Questions that come up
Is IF NOT EXISTS enough for migrations?
It handles 'run twice', not 'changed since'. If someone added a column by hand, IF NOT EXISTS will not notice the drift. That gap is what migration tools with a versions table (see the schema-version recipe) are for.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.