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?
Asked
Active
Viewed 2.1k times
36
-
1Possible duplicate of [One of the column between two columns should be NOT NULL. How to enforce it in schema?](http://stackoverflow.com/questions/7017871/one-of-the-column-between-two-columns-should-be-not-null-how-to-enforce-it-in-s) – JohnnyHK Mar 10 '16 at 00:16
-
2@JohnnyHK not duplicate as this question is about 'at least one of two' and that one is about 'only one of two' – nahab Mar 15 '17 at 10:46
3 Answers
46
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

Filip De Vos
- 11,568
- 1
- 48
- 60
28
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 )

nahab
- 1,308
- 17
- 38
-
2This works if the columns have the same datatype. Otherwise the system will try to convert in order to check this constraint – GôTô Jul 23 '21 at 19:31
0
Another option:
CONSTRAINT at_least_one_not_null CHECK (
COALESCE((col1)::BOOLEAN::INTEGER, 0) +
COALESCE((col2)::BOOLEAN::INTEGER, 0) > 0
)

Reinier Garcia
- 1,002
- 1
- 11
- 19