1

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: e.g.: 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

5
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Apr 5, 2017 at 16:25
  • 1
    This do not only check to not have two nulls, this force to have one and only one null. Commented Apr 5, 2017 at 16:27
  • @marc_s using postgresql sorry Commented Apr 6, 2017 at 10:50
  • @iguypouf this is meant to be. Only one of them (column0 or column1) must be not null Commented Apr 6, 2017 at 10:51
  • Look at the Zak's answer, he said same as I. Commented Apr 12, 2017 at 13:21

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Good catch! The question didn't say that two non null values should fail.
@Zack what a dumb I am! I should have simplify my logic, through this way. Is better for reading! Thx
1

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    |
+---------+---------+

1 Comment

Thank you for mentioning rextester tool @SqlZim, I was having other problem resulting in failure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.