Skip to content
Advertisement

Are SQL Server unique constraints “Silent” or do they raise an exception?

I want to prevent inserting duplicate values into my tables. At first, I added code to check if the value already existed in the database, but that seems like a lot of overhead / wasted time if I can prevent it at the DDL level.

So I found this and changed one of my tables (as an example) from this:

to this:

I want the constraint to prevent a second identical ActorId without whin[g]ing about it. IOW, just bypass it, don’t tell me about it, don’t stop the app or throw an exception.

Is this how it works (silently), or will it throw an exception?

Advertisement

Answer

Let’s try that:

A unique constraint violation does raise an error. This is how the database lets you know that something went wrong.

SQL Server has built-in no option (that I know about) to ignore such error, unlike many other databases (MySQL, Postgres, SQLite…). A workaround is to rewrite the insert with not exists and a subquery:

Another option is the merge statement:

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