简体   繁体   中英

SQL Constraint conditional Check: if column0 is null, column1 is not null and vice versa

I have this question around SQL constraints, in order to achieve following behavior:

TableA has two columns column0 and column1, which only one can be NULL on data entry: eg: if column0 is null, column1 can't be null if column1 is null, column0 can't be null

To achieve this, I've build following SQL constraints:

CONSTRAINT column01_not_null_chk
CHECK (
  ( column0 IS NOT NULL
  AND column1 IS NULL )
OR
  ( column1 IS NOT NULL
  AND column0 IS NULL ) )

is this correct to achieve my behavior? Because all SQL are rejected because of this constraint

The condition you described means that at least one of them has to have value. So your constraint should be corrected to:

CONSTRAINT column01_not_null_chk
CHECK (column0 IS NOT NULL OR column1 IS NOT NULL)

Seems to work fine on SQL Server:

create table t (
     column0 int null
   , column1 int null
, CONSTRAINT column01_not_null_chk
CHECK (
  ( column0 IS NOT NULL
  AND column1 IS NULL )
OR
  ( column1 IS NOT NULL
  AND column0 IS NULL ) )
);

insert into t values (null,1),(1,null);

select * from t;
--insert into t values (null,null) /* fail */
--insert into t values (1,1) /* fail */

rextester demo : http://rextester.com/OQZNE39497

returns:

+---------+---------+
| column0 | column1 |
+---------+---------+
| NULL    | 1       |
| 1       | NULL    |
+---------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM