// SQL snippet

Add a foreign key if it does not exist

Replayed migrations choke on duplicate constraint names. Guard FK creation on the constraint name and it becomes safely re-runnable.

Main statement
PostgreSQL
Couvre également
SQL Server MySQL

The task

Rollouts and rollbacks mean the same foreign key can be created more than once, and the second attempt should be a no-op instead of an error.

The snippet

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

PostgreSQL
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'fk_orders_customer'
      AND conrelid = 'public.orders'::regclass
  ) THEN
    ALTER TABLE public.orders
      ADD CONSTRAINT fk_orders_customer
      FOREIGN KEY (customer_id) REFERENCES public.customers (id);
  END IF;
END $$;

Fonctionnement

The guard checks pg_constraint for the constraint name on that specific table, so the ALTER runs only the first time. On a large orders table the plain ADD CONSTRAINT checks every customer_id while holding a SHARE ROW EXCLUSIVE lock on both tables, which blocks writes to them until it finishes. Splitting it with NOT VALID (add now, VALIDATE CONSTRAINT later) keeps that lock momentary; the validation then runs under a weaker lock that lets reads and writes continue.

Variations

PostgreSQL: big table, no long lock

PostgreSQL
ALTER TABLE orders
  ADD CONSTRAINT fk_orders_customer
  FOREIGN KEY (customer_id) REFERENCES customers (id)
  NOT VALID;
-- later, without blocking writes:
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;

SQL Server

SQL Server
IF NOT EXISTS (
    SELECT 1 FROM sys.foreign_keys
    WHERE name = 'FK_Orders_Customers'
      AND parent_object_id = OBJECT_ID('dbo.Orders'))
    ALTER TABLE dbo.Orders
        ADD CONSTRAINT FK_Orders_Customers
        FOREIGN KEY (customer_id) REFERENCES dbo.Customers (id);

MySQL

MySQL
SET @sql := IF(EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_schema = DATABASE()
      AND table_name = 'orders'
      AND constraint_name = 'fk_orders_customer'
      AND constraint_type = 'FOREIGN KEY'),
  'DO 0',
  'ALTER TABLE orders ADD CONSTRAINT fk_orders_customer
     FOREIGN KEY (customer_id) REFERENCES customers (id)');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- InnoDB adds an index on customer_id if none exists

Questions that come up

Why does adding my foreign key fail?

Usually one of three things. Existing child rows point at parents that do not exist; find them with SELECT ... FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE o.customer_id IS NOT NULL AND c.id IS NULL. The two columns have different types (int against bigint, or signed against unsigned on MySQL). Or the referenced column is not covered by a primary key or unique constraint.

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.