Question

I spent hours last night trying to figure out what's wrong with the check constraint below. I want to enforce the following rule:

  • Either all rows are null
  • Or Col1 is not null and only one of the other columns is not null (if col4 is set, it should be set to true)

I'm able to insert rows with only Col1 set, but I want an error thrown instead.

    create table TestTable
    (
        Col1 varchar(10) null,
        Col2 varchar(10) null,
        Col3 varchar(10) null,
        Col4 bit null,
    )


    alter table TestTable add constraint X check
    (
        (Col1 is null and Col2 is null and Col3 is null and Col4 is null) or
        (
            Col1 is not null and
            (
                (Col2 is not null and Col3 is null and Col4 is null) or
                (Col2 is null and Col3 is not null and Col4 is null) or
                (Col2 is null and Col3 is null and Col4 = 1)
            )
        )
    )
Was it helpful?

Solution

Equality comparison doesn't work with NULLs:

alter table TestTable add constraint X check
(
    (Col1 is null and Col2 is null and Col3 is null and Col4 is null) or
    (
        Col1 is not null and
        (
            (Col2 is not null and Col3 is null and Col4 is null) or
            (Col2 is null and Col3 is not null and Col4 is null) or
            (Col2 is null and Col3 is null and (Col4 is not null and Col4 = 1))
        )
    )
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top