Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Constraining a set of columns so at least one is not NULL

I want to have a SQL table with two columns. One is a key into another table, the other holds a string literal. The idea is phone numbers can be entered either exactly (in which case the ID into the phonebook table is used) or as a wildcard (in which the string literal is used).

This means that one column in the table will hold a value, and the other will hold a NULL.

Is it possible to constrain a table in such a way that one column must have a value, and the other must be NULL? If both columns are NULL or both have a value, then the row is invalid.

I have a feeling that MySQL can't do this (as it doesn't seem to have a comprehensive toolbox when it comes to constraints), but it couldn't hurt to ask.

like image 342
GordonM Avatar asked Apr 08 '11 11:04

GordonM


2 Answers

I am not aware of a way to enforce such a constraint.

As a workaround, you may consider to have two different columns: If you have one column for the data - containing the phonebook id or the string literal, and another column for the data type - either 'exact' or 'wildcard' -, you can set a NOT NULL constraint to both columns. One obvious drawback is that you cannot have a FK constraint to the phonebooks table any more.

like image 169
titanoboa Avatar answered Oct 10 '22 11:10

titanoboa


You can make triggers to run on before the insert, to check the values and determine if the insert or update should happen or not. A good example for how to create triggers like this can be found here: https://dba.stackexchange.com/questions/43284/two-nullable-columns-one-required-to-have-value

like image 32
Drogos Avatar answered Oct 10 '22 09:10

Drogos