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?
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 .
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.
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.
NULL values are allowed in case of a unique key. These can also be used as foreign keys for another table.
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.
From the docs:
"a UNIQUE index permits multiple NULL values for columns that can contain NULL"
This applies to all engines but BDB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With