Home > Software design >  Azure SQL DB allow NULL values for UNIQUE constraint columns
Azure SQL DB allow NULL values for UNIQUE constraint columns

Time:02-25

How can I set a UNIQUE constraint in Azure SQL database that allows NULL values in the column?

The below workaround from SQL Server doesn't seem to work in Azure SQL:

CREATE UNIQUE NONCLUSTERED INDEX [IX_Email] ON [dbo].[Users]([Email] ASC)
WHERE ([Email] IS NOT NULL);

CodePudding user response:

The error, which is in the comments is telling you the problem:

Violation of UNIQUE KEY Constraint "UQ_Users_5120...". Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is ().

Firstly, notice that the error states "UNIQUE KEY Constraint", emphasis mine. Not Index, Constraint. Also note that name of said constraint: UQ_Users_5120... That isn't the name of the object you created (IX_Email).

You can replicate this problem with the following:

CREATE TABLE dbo.SomeTable (SomeColumn varchar(10) NULL);
GO
--Create a UNIQUE Constraint
ALTER TABLE dbo.SomeTable ADD CONSTRAINT UQ_SomeColumn UNIQUE (SomeColumn);
GO
--Create a filtered unique index
CREATE UNIQUE NONCLUSTERED INDEX UX_SomeColumn_NotNull ON dbo.SomeTable(SomeColumn)
WHERE SomeColumn IS NOT NULL;
GO
--Initial Insert
INSERT INTO dbo.SomeTable (SomeColumn)
VALUES('asdfasd'),
      ('asdasd'),
      (NULL);
GO
--Insert another dupe, non NULL value. Fails
--This violates constraint 'UQ_SomeColumn'
INSERT INTO dbo.SomeTable (SomeColumn)
VALUES('asdfasd');
GO
--Insert another dupe, NULL value. Fails
--This violates constraint 'UQ_SomeColumn'
INSERT INTO dbo.SomeTable (SomeColumn)
VALUES(NULL);
GO

You can fix this my dropping your UNIQUE CONSTRAINT. We don't have the full name, but for the above example it would be the following:

ALTER TABLE dbo.SomeTable DROP CONSTRAINT UQ_SomeColumn;
GO

And then we can test again:

--Insert another dupe, non NULL value. Fails
--Cannot insert duplicate key row in object 'dbo.SomeTable' with unique index 'UX_SomeColumn_NotNull'. The duplicate key value is (asdfasd).
INSERT INTO dbo.SomeTable (SomeColumn)
VALUES('asdfasd');

--Insert another dupe, NULL value. Success
INSERT INTO dbo.SomeTable (SomeColumn)
VALUES(NULL);
GO

Notice as well, that the error for the duplicate value is completely different now. It mentions a unique index, not a unique key constraint, and has the name of the unique filtered index created, not something else.

  • Related