Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MySQL ignore null values on unique constraints?

I have an email column that I want to be unique. But I also want it to accept null values. Can my database have 2 null emails that way?

like image 765
Hugo Mota Avatar asked Sep 14 '10 19:09

Hugo Mota


People also ask

Does unique constraint accept NULL values?

You can insert NULL values into columns with the UNIQUE constraint because NULL is the absence of a value, so it is never equal to other NULL values and not considered a duplicate value. This means that it's possible to insert rows that appear to be duplicates if one of the values is NULL .

Can Unique have NULL values in SQL?

Unique fields in SQL Server are created using unique constraints or unique indexes, furthermore, each unique constraint uses a unique index. Regardless of using unique constraint or unique index, the field can accept null values, however the uniqueness will result in only accepting a single row with null value.

Does unique have to be not null?

The columns specified in a unique constraint must be defined as NOT NULL. The database manager uses a unique index to enforce the uniqueness of the key during changes to the columns of the unique constraint. Unique constraints can be defined in the CREATE TABLE or ALTER TABLE statement using the UNIQUE clause.

Can unique key contains NULL value?

NULL values are allowed in case of a unique key. These can also be used as foreign keys for another table.


2 Answers

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

CREATE TABLE table1 (x INT NULL UNIQUE); INSERT table1 VALUES (1); INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x' INSERT table1 VALUES (NULL); INSERT table1 VALUES (NULL); SELECT * FROM table1; 

Result:

x NULL NULL 1 

This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

like image 161
Mark Byers Avatar answered Oct 22 '22 06:10

Mark Byers


From the docs:

"a UNIQUE index permits multiple NULL values for columns that can contain NULL"

This applies to all engines but BDB.

like image 43
Matthew Flaschen Avatar answered Oct 22 '22 06:10

Matthew Flaschen