Unique constraint that allows multiple nulls and empty strings

T-SQL’s UNIQUE constraint allows for NULL values, but only one null value is allowed per column. There is, however, a nifty little way around this, via the WHERE clause.

For example, here’s a UNIQUE constraint that makes sure an ID is unique but allows for both multiple NULL values and multiple empty strings:

CREATE UNIQUE NONCLUSTERED INDEX [UNIQUE_ID] ON [dbo].[tblParticipant]
(
[ID] ASC
)
WHERE ([ID] IS NOT NULL AND [ID] <> ”)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s