38

I'm trying to put check constraint on existing column.

Is there any way to achieve this from PostgreSQL?

2
  • 2
    Sure. What did you try so far? Did you check the documentation? Commented Feb 12, 2015 at 15:23
  • @frlan Postgres is a perfectly acceptable alternative name for PostgreSQL Commented Feb 13, 2015 at 7:53

4 Answers 4

60

Use alter table to add a new constraint:

alter table foo 
   add constraint check_positive check (the_column > 0);

More details and examples are in the manual:
http://www.postgresql.org/docs/current/static/sql-altertable.html#AEN70043

Edit

Checking for specific values is done in the same way, by using an IN operator:

alter table foo 
   add constraint check_positive check (some_code in ('A','B'));
Sign up to request clarification or add additional context in comments.

4 Comments

How do you put enum checks in the constraint?
What is an enum check?
My question was directed to @Passionate Developer
Like constriant for ("ABC", "DEF")
9

If you are okay with (or want) Postgres to generate a constraint name you can use the following shorthand syntax.

ALTER TABLE foo
    ADD CHECK (column_1 > 2);

Comments

2

You can add a new constraint with with alter table command. From documentation this example:

ALTER TABLE distributors 
ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT;

You will have to replace constraint name as well as table name and content by your local requirements.

Comments

1

This should do it:

create table test (
    id serial 
);

alter table test
add constraint id_not_null
check (id is not null);

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.