I'm using PostgreSQL 9.1.
I have a table common.client_contact
where I created foreign key using this code:
ALTER TABLE common.client_contact
ADD FOREIGN KEY (contact_id) REFERENCES common.contact_item(id);
If I execute this code, I will get several foreign keys with different names (like client_contact_contact_id_fkey1
, client_contact_contact_id_fkey2
, client_contact_contact_id_fkey3
and so on).
So, before creating new constraint, I need to check if it's exists.
I check if this constraint exists in pg_constraint
table:
SELECT * FROM pg_constraint WHERE conname = 'client_contact_contact_id_fkey'
And now I need to combine them together. Something like
IF NOT EXISTS
(SELECT * FROM pg_constraint WHERE conname = 'client_contact_contact_id_fkey')
ALTER TABLE common.client_contact
ADD CONSTRAINT client_contact_contact_id_fkey
FOREIGN KEY (contact_id) REFERENCES common.contact_item(id)
or just
ALTER TABLE common.client_contact
ADD FOREIGN KEY IF NOT EXISTS (contact_id) REFERENCES common.contact_item(id)
But these two queries are produce syntax error. So, how can I do it in PostgreSQL?