7

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?

4
  • 1
    Are both columns allowed to be non-NULL? I.e. is this "at least one column must not be NULL" or "exactly one column must not be NULL"? Commented Aug 17, 2015 at 14:44
  • 2
    Neither. They both can be NOT NULL, but they both cannot be NULL. The only combinations allowed are NULL, NOT NULL or NOT NULL, NULL or NOT NULL, NOT NULL. Never it can be NULL, NULL. Commented Aug 18, 2015 at 7:53
  • 1
    How is that neither? It sounds exactly like "at least one column must not be NULL". Commented Aug 18, 2015 at 7:54
  • @Damien_The_Unbeliever, yes you are correct. I was thinking you meant one column must be NULL. Sorry. My bad. Commented Aug 18, 2015 at 8:27

2 Answers 2

11

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

Comments

2

What about CHECK Constraints?

ADD CONSTRAINT chkIsNotNull CHECK (spiceId is not null or spiceDes is not null);

Comments

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.