Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql compound keys and null values

Tags:

I have noticed that if I have a unique compound keys for two columns, column_a and column_b, then my sql ignores this constraint if one column is null.

E.g.

if column_a=1 and column_b = null I can insert column_a=1 and column_b=null as much as I like

if column_a=1 and column_b = 2 I can only insert this value once.

Is there a way to apply this constraint, other than maybe changing the columns to Not Null and setting default values?

like image 713
stevebot Avatar asked Jun 21 '10 16:06

stevebot


People also ask

Can a compound primary key be NULL?

Hi, In composite primary key columns you cannot pass null values. Each column defined as a primary key would be validated so that null values are not passed on to them. If you have given a Unique constraint then we have a chance of NULL values being accepted.

Can a partial key be NULL?

Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input. Per definition, NULL cannot be part of a successful comparison.

Can a primary key be one NULL attribute?

Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields.

Can composite unique key be NULL?

You cannot have a null field as part of a primary key, but you can create a unique composite index which is not a primary key and this can include a null field.


1 Answers

http://dev.mysql.com/doc/refman/5.0/en/create-index.html

"A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL."

So, no, you can't get MySQL to treat NULL as a unique value. I guess you have a couple of choices: you could do what you suggested in your question and store a "special value" instead of null, or you could use the BDB engine for the table. I don't think this minor difference in behaviour warrants making an unusual choice of storage engine, though.

like image 186
Hammerite Avatar answered Sep 21 '22 01:09

Hammerite