I have implemented this code to add acheck constraint after creating the table
ALTER TABLE recruitment_data.candidate_experiences ADD CONSTRAINT chk_experience_dates CHECK ( experience_end_date IS NULL OR experience_end_date >= experience_start_date);but it gives an error when I run it more than once:
ERROR: constraint "chk_experience_dates" for relation "candidate_experiences" already exists
Since it is impossible to runADD CONSTRAINTIF NOT EXISTS, is there any other way to run it twice without creating duplicate constraints, and without having to catch and handle or ignore the error?
What should I do to make this codere-runnable?
- 1Please add you Postgres version, the definition of the table in question and some example
insertstatements, demonstrating which are allowed and which this constraint is supposed to prevent. What you're showing is perfectly valid but your mention ofif not existssuggests you want this constraint to be able to compare against other rows, which acheckisn't supposed to do. My guess is you want some sort ofexcludeorunique..without overlaps.Zegarek– Zegarek2025-11-20 12:32:52 +00:00CommentedNov 20 at 12:32 - 1If you're getting an error, attach the full error message and the code that caused it.Zegarek– Zegarek2025-11-20 12:37:57 +00:00CommentedNov 20 at 12:37
- 118.0 is the version and error message is
ERROR: constraint "chk_experience_dates" for relation "candidate_experiences" already exists. It is adding the constraint when this code is executed for the first time, but if I try to execute it one more time, it gives error that I have written above. Since it is impossible to writeADD CONSTRAINT IF NOT EXISTS, is there any other way to run it twice without producing duplicate or error that it already exists?Beliz Yazici– Beliz Yazici2025-11-20 13:01:46 +00:00CommentedNov 20 at 13:01 - 1Do you want it to drop and recreate, or to just ignore if it exists (regardless of what the constraint predicate is)?Charlieface– Charlieface2025-11-20 13:34:34 +00:00CommentedNov 20 at 13:34
- I would like to ignore if it already existsBeliz Yazici– Beliz Yazici2025-11-20 14:06:29 +00:00CommentedNov 20 at 14:06
1 Answer1
You're correct thatALTER TABLE..ADD CONSTRAINT doesn't support anIF NOT EXISTS clause. But,ALTER TABLE:
- allows you to combine multiple
ALTERstatements into one:All the forms of
ALTER TABLEthat act on a single table, exceptRENAME,SET SCHEMA,ATTACH PARTITION, andDETACH PARTITIONcan be combined into a list of multiple alterations to be applied together. - offers an opposite statement
DROP CONSTRAINT IF EXISTS, that does support this clause
ALTER TABLE recruitment_data.candidate_experiences DROP CONSTRAINT IF EXISTS chk_experience_dates, ADD CONSTRAINT chk_experience_dates CHECK ( experience_end_date IS NULL OR experience_end_date >= experience_start_date);3 Comments
alter table based the contents ofpg_constraint.Explore related questions
See similar questions with these tags.


