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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
sat
  • 5,489
  • 10
  • 63
  • 81

1 Answers1

12

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.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Eevee
  • 47,412
  • 11
  • 95
  • 127