Hello friends,
Sometimes we get the data that needs to be unique but can also get NULL records. Existing ways to achieve uniqueness doesn’t allow NULLs (Primary Key) or allow max one NULL (Unique Constraint).
Let’s take an example to understand this better. Suppose, you have an Employee
table with fields like Id, FirstName, MiddleName, LastName, Email etc. As per requirement, email needs to be unique (if supplied), however, users are also allowed to register without entering email and hence in the database Email
is a nullable field.
So how would you achieve the Email
uniqueness along with having more than one NULLs.
CREATE UNIQUE NONCLUSTERED INDEX [UX_Employee_Email] ON [dbo].
Employee
WHERE Email IS NOT NULL
Above code will ensure that Email
doesn’t have duplicate data however it may store more than one NULLs.
I hope you may have liked the tip. You share your comments.