Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Allow NULL on two columns but not both

I have a table that is simply a lookup with two columns.

spiceId - INT
spiceDes - VARCHAR(100)

Now, I have the columns set as allow NULL for both columns, but I would like to add a constraint where it should be that only one column could be NULL for any record. That is spiceID and spiceDes could not, both be NULL.

How can I add this constraint?

like image 457
PaulFrancis Avatar asked Aug 17 '15 14:08

PaulFrancis


2 Answers

Use Alter table to add a check constraint on your table:

ALTER TABLE tableName
ADD  CONSTRAINT CK_nulltest
CHECK (spiceId IS NOT NULL OR spiceDes IS NOT NULL);
like image 65
Zohar Peled Avatar answered Oct 02 '22 13:10

Zohar Peled


What about CHECK Constraints?

ADD CONSTRAINT chkIsNotNull CHECK (spiceId is not null or spiceDes is not null);
like image 39
Arsen Mkrtchyan Avatar answered Oct 02 '22 15:10

Arsen Mkrtchyan