I need a check constraint on two columns, at least one must be not null
Asked Answered
R

3

38

I have a table in SQL Server with two numeric columns. At least one of these numeric fields must be filled. How do I write a check constraint to verify this?

Rudie answered 29/9, 2014 at 14:38 Comment(2)
Possible duplicate of One of the column between two columns should be NOT NULL. How to enforce it in schema?Kristofor
@Kristofor not duplicate as this question is about 'at least one of two' and that one is about 'only one of two'Elgon
W
52

This can be done with a check constraint that verifies null value and matches the result with or

create table #t (i int
               , j int
               , constraint chk_null check (i is not null or j is not null))

The following are the test cases

insert into #t values (null, null) --> error
insert into #t values (1, null) --> ok
insert into #t values (null, 1) --> ok
insert into #t values (1, 1) --> ok
Woodpecker answered 29/9, 2014 at 14:44 Comment(0)
E
31

late answer, but here is a solution for Sql Server for any number of columns to check:

CONSTRAINT CK_one_is_not_null CHECK (COALESCE(col1, col2, col3) IS NOT NULL )
Elgon answered 15/3, 2017 at 10:48 Comment(2)
This works if the columns have the same datatype. Otherwise the system will try to convert in order to check this constraintFuegian
ISNULL(a,b) can be used if there are two columns, but COALESCE is more general.Equidistance
Z
0

Another option:

CONSTRAINT at_least_one_not_null CHECK (
            COALESCE((col1)::BOOLEAN::INTEGER, 0) +
            COALESCE((col2)::BOOLEAN::INTEGER, 0) > 0
    )
Zemstvo answered 12/6, 2023 at 18:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.