Question

I have a column in table that have a Unique constraint.

Now in general is it best to check in database if the value for that column is duplicate or not OR is it better to handle the exception it produces in a try catch ?

Will the answer be general or there will be cases like if it was only a simple table like for usernames column for example or if table had many columns and foreign keys.

Edit:

After reading both answers i think this matter is arguable, because it may cause performance issue for either database on pre-check or code issue when catching exception but i think i would prefer catching exception especially if the unique value is subject to update.

Was it helpful?

Solution

To check the database before trying the insert, you either end up introducing a race condition, or you take out a key-range-lock (which could cause blocking, etc). In either event, it is going to have to check for the duplicate anyway when you actually insert, so you're purely adding work (and possibly an extra round trip).

It does depend a bit on how likely it is to be a duplicate, but in the majority of cases: this is exceptional, and should probably be handled as such - via an exception when the database reports a problem. BUT: there will always be some scenarios where it is sensible to check ahead of time - and in those cases, you might do both. For example, in a data-entry application, as soon as the user enters a value into the key input here, and tabs to the next control - you might check the database in the background to verify that there is not already a value: but - you still need to be prepared for the fact that data changes constantly, from multiple sources - so no matter how you check, it could still be a duplicate at the time you insert.

OTHER TIPS

I usually add validation/checks before the exception hits, this way helps me plan what action I should do when the validation fails. Although constraints may do the same thing, I believe throwing an exception is expensive as it will create additional objects. But in general, it is much preferable to have multiple checks - validation, constraint etc..with this you will be sure of data integrity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top