Postgres: Add constraint if it doesn’t already exist

A possible solution is to simply use DROP IF EXISTS before creating the new constraint.

ALTER TABLE foo DROP CONSTRAINT IF EXISTS bar;
ALTER TABLE foo ADD CONSTRAINT bar ...;

Seems easier than trying to query information_schema or catalogs, but might be slow on huge tables since it always recreates the constraint.

Edit 2015-07-13:
Kev pointed out in his answer that my solution creates a short window when the constraint doesn’t exist and is not being enforced. While this is true, you can avoid such a window quite easily by wrapping both statements in a transaction.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)