I have a table that contains, for example, two fields that I want to make unique within the database. For example:
create table Subscriber (
ID int not null,
DataSetId int not null,
Email nvarchar(100) not null,
...
)
The ID column is the primary key and both DataSetId and Email are indexed.
What I want to be able to do is prevent the same Email and DataSetId combination appearing in the table or, to put it another way, the Email value must be unique for a given DataSetId.
I tried creating a unique index on the columns
CREATE UNIQUE NONCLUSTERED INDEX IX_Subscriber_Email
ON Subscriber (DataSetId, Email)
but I found that this had quite a significant impact on search times (when searching for an email address for example - there are 1.5 million rows in the table).
Is there a more efficient way of achieving this type of constraint?
The index you defined on
(DataSetId, Email)
cannot be used for searches based on email. If you would create an index with theEmail
field at the leftmost position, it could be used:This index would server both as a unique constraint enforcement and as a means to quickly search for an email. This index though cannot be used to quickly search for a specific
DataSetId
.The gist of it if is that whenever you define a multikey index, it can be used only for searches in the order of the keys. An index on
(A, B, C)
can be used to seek values on columnA
, for searching values on bothA
andB
or to search values on all three columnsA
,B
andC
. However it cannot be used to search values onB
or onC
alone.I assume that only way to enter data into that table is through SPs, If that's the case you can implement some logic in your insert and update SPs to find if the values you are going to insert / update is already exists in that table or not.
Something like this