In Data Manipulation, the UNIQUEconstraint in SQLServer will restrict the records such that no two records have similar values either in this column or in one or many other columns. Nonetheless, SQL Server permitting duplication of NULL in a column that has UNIQUE constraint. This behavior is that SQL Server operates
NULL as the unknown value and the two NULLs are not equal.
Behavior of UNIQUE Constraint with
NULLs
If a column has UNIQUE constraint, multiple NULL values can be stored in this column because SQL Server does not support uniqueness constraint for
NULL.
Nonetheless, any value in that column cannot be NULL if other similar values already exist or are present in the database.
Example:
-- Create a table with a UNIQUE constraint
CREATE TABLE Employee (
EmployeeID INT,
Email NVARCHAR(100) UNIQUE
);
-- Insert values
INSERT INTO Employee (EmployeeID, Email) VALUES (1, 'john@example.com'); -- Valid
INSERT INTO Employee (EmployeeID, Email) VALUES (2, 'jane@example.com'); -- Valid
INSERT INTO Employee (EmployeeID, Email) VALUES (3, NULL); -- Valid
INSERT INTO Employee (EmployeeID, Email) VALUES (4, NULL); -- Valid (allows duplicate NULLs)
-- Attempt to insert a duplicate non-NULL value
INSERT INTO Employee (EmployeeID, Email) VALUES (5, 'john@example.com'); -- Error: Violation of UNIQUE constraint
Hope it helps!!
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In Data Manipulation, the
UNIQUEconstraint in SQL Server will restrict the records such that no two records have similar values either in this column or in one or many other columns. Nonetheless, SQL Server permitting duplication of NULL in a column that hasUNIQUEconstraint. This behavior is that SQL Server operatesNULLas the unknown value and the twoNULLsare not equal.Behavior of
UNIQUEConstraint withNULLsUNIQUEconstraint, multipleNULLvalues can be stored in this column because SQL Server does not support uniqueness constraint forNULL.NULLif other similar values already exist or are present in the database.Example:
Hope it helps!!