Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: Add constraint if it doesn't already exist

Does Postgres have any way to say ALTER TABLE foo ADD CONSTRAINT bar ... which will just ignore the command if the constraint already exists, so that it doesn't raise an error?

like image 540
Paul A Jungwirth Avatar asked Jul 23 '11 16:07

Paul A Jungwirth


People also ask

How do you add primary key if not exists PostgreSQL?

Postgresql add primary key if not exists We will alter the table items by adding a new column name which is customer_name. Let's check the syntax. ALTER TABLE table_name ADD COLUMN column_name VARCHAR NOT NULL; Let's check the query again by adding the column customer_name.

How do you add a constraint to an existing table in Postgres?

Here is the generic syntax to add a constraint: ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint_definition; For example, to add a UNIQUE constraint to the table customers on the column customer_id: ALTER TABLE customers ADD CONSTRAINT uniquectm_const UNIQUE (customer_id);

How do I add a primary key constraint to an existing table in PostgreSQL?

In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement. You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.


1 Answers

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.

like image 127
Webmut Avatar answered Oct 22 '22 10:10

Webmut