'Add constraint if not exists

I want to add the 'check' constraint to some table, but firstly I have to check if that constraint exists. I have some error in my SQL script. What is the corret way to do it ?

   ALTER TABLE public.ELEMENTS ADD CONSTRAINT IF NOT EXISTS elements_check CHECK ((t1_id IS NOT NULL) OR (t2_id IS NOT NULL));


Solution 1:[1]

According to the manual :

  1. ALTER TABLE ... DROP CONSTRAINT IF EXISTS do exist
  2. ALTER TABLE ... ADD CONSTRAINT IF NOT EXISTS doesn't exist

so you have to execute 1. before 2. :

ALTER TABLE public.ELEMENTS DROP CONSTRAINT IF EXISTS elements_check ;

ALTER TABLE public.ELEMENTS ADD CONSTRAINT elements_check CHECK ((t1_id IS NOT NULL) OR (t2_id IS NOT NULL));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1