8
create table test (
    col1 varchar(20),
    col2 varchar(20)
)
  1. When col1 has value '1', col2 cannot be null.
  2. When col1 has any other value, col2 can be null.

Is there a way to write a check constraints based on values of particular columns?

1 Answer 1

13

You can write a table-level constraint, sure.

CREATE TABLE test (
    col1 VARCHAR(20),
    col2 VARCHAR(20),
    CHECK (col1 != '1' OR col2 IS NOT NULL)
);

Either col1 isn't '1' (and col2 can be anything), or col1 is '1' (and col2 can't be null).

See the third example in the manual.

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.