This is one of those classic “gotchas” that leave you scratching your head for hours. This is not only limited to MySQL as this behavious is defined in the SQL92 Specifications.
Just say you have a table like this:
Create table test (
x smallint not null,
y char(5) default null,
Unique Key `s`(x, y)
) ENGINE=MyISAM
And then execute the following inserts - you would expect that the final insert would be caught by the Unique Key. Wrong
Insert into test values (1, ‘dan’, ‘yes’), (2, ‘joe’, ‘no’), (3, NULL,‘maybe’),(4,NULL,’maybe’
All 4 are inserted into the database.
From MySQL:
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.
Anda further explanation from MySQL Developers:
http://bugs.mysql.com/bug.php?id=4140
Hopefully this saves someone some head scratching.