3

I need to add a Constraint if not exists and am hitting the following error. Note that a similar if not exists for a new Column, right above it, does work. There's some syntax error when adding a Constraint, am I missing something?

alter table requests_t
add constraint if not exists 
valid_bias_check CHECK (bias_flag::text = ANY (ARRAY['Y'::character varying::text, 'N'::character varying::text]));

Error

ERROR:  syntax error at or near "not"
LINE 2: add constraint if not exists 

enter image description here

4
  • 4
    The answer is simple: as documented in the manual there is no option if not exists when using add constraint Commented Mar 18, 2022 at 14:12
  • That's a shame. Any equivalents possible? Commented Mar 18, 2022 at 14:19
  • Also, why is the following answer provided (and accepted)? stackoverflow.com/a/43755195/1005607 Commented Mar 18, 2022 at 14:20
  • 1
    That question is about H2, not Postgres Commented Mar 18, 2022 at 14:26

1 Answer 1

5

Since Postgres doesn't support this syntax with constraints (see a_horse_with_no_name's comment), I rewrote it as:

alter table requests_t
drop constraint if exists valid_bias_check;

alter table requests_t
add constraint 
valid_bias_check CHECK (bias_flag::text = ANY (ARRAY['Y'::character varying::text, 'N'::character varying::text]));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.