Skip to content
Advertisement

Duplicate check using SELECT or rely on unique index?

Using SQL Server 2012. I want to insert unique strings into a table. I always want to return the row ID of the unique string. Now, this can be accomplished in two ways.

Which solution is the best?

This is the table in question:

Solution 1:

SELECT first to check if the string exists. If it does, return its ID. Otherwise, INSERT a new row and return the newly created ID.

Solution 2:

INSERT first. If the insert violates the UNIQUE INDEX, a SELECT is issued.

Solution 3:

Ideas? 🙂

Advertisement

Answer

In my testing I have found that it is much more efficient to check for the violation first instead of letting SQL Server try and fail, especially when the failure rate is expected to be significant (and at best they perform about the same overall, when the failure rate is low). Details here and here.

In addition to performance, another reason to not rely on the constraint to raise an error is that tomorrow someone could change or drop it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement