// SQL snippet

Add a column if it does not exist

Migrations re-run, roll back and get replayed on fresh databases, so DDL should be idempotent. This is the add-column-if-missing pattern per engine.

Main statement
PostgreSQL
还支持
SQL Server MySQL SQLite

The task

The same migration script runs on many environments at different schema versions, and on the ones that already have the column the statement must simply do nothing.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
ALTER TABLE users
  ADD COLUMN IF NOT EXISTS last_login_at timestamptz;

工作原理

PostgreSQL's ADD COLUMN IF NOT EXISTS (available since 9.6) turns the statement into a no-op with a NOTICE when the column is already there, so re-running a migration is harmless. A nullable column with no default is a catalog-only change. Since PostgreSQL 11 that also holds for a column with a constant default, even NOT NULL, because the default is stored once and filled in at read time; a volatile default such as clock_timestamp() still rewrites the table.

Variations

SQL Server

SQL Server
IF COL_LENGTH('dbo.Users', 'last_login_at') IS NULL
    ALTER TABLE dbo.Users
        ADD last_login_at DATETIMEOFFSET NULL;

MySQL

MySQL
-- no native IF NOT EXISTS on ADD COLUMN; check first
SET @col := (SELECT COUNT(*)
             FROM information_schema.columns
             WHERE table_schema = 'mydb'
               AND table_name = 'users'
               AND column_name = 'last_login_at');
SET @sql := IF(@col = 0,
    'ALTER TABLE users ADD COLUMN last_login_at DATETIME NULL',
    'SELECT ''column already exists''');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLite

SQLite
-- no IF NOT EXISTS and no procedural IF; check from the
-- application, then alter
SELECT COUNT(*) FROM pragma_table_info('users')
WHERE name = 'last_login_at';
-- if 0:
ALTER TABLE users ADD COLUMN last_login_at TEXT;

Questions that come up

Does ADD COLUMN lock the table?

Briefly, on modern versions. PostgreSQL 11+ and SQL Server 2012+ Enterprise add a column with a constant default as a metadata change, and MySQL 8.0.12+ uses ALGORITHM=INSTANT for most ADD COLUMN cases. Each still needs a short exclusive metadata lock, which has to wait for running queries on the table and blocks new ones while it waits, so set a lock timeout. A volatile default, or older versions, mean a full table rewrite.

Keep reading

// snippets are better with a schema brain

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.