What is the recommended practice for detecting a duplicate?
843859Jun 26 2008 — edited Jan 19 2015Hi
Although this question is pretty basic, I can not seem to find an existing thread that addresses it fully.
My question is as follows:
What is the recommended way to detect a duplicate record when performing an 'INSERT'?
In my scenario, I have a table of users with a username column that is 'unique'. When a user registers, I need to tell him if the username already exists.
One option, of course, is to perform a 'SELECT' query to check if the username exists, and only then perform the 'INSERT'. However, if 2 users register almost simultaneously, the username might be inserted after the 'SELECT' but before the 'INSERT'.
Another option is to catch the SQL Exception. However, as far as I can see, the exact Exception will be vendor specific. If the code is going to be vendor-neutral, it will be challenging to pin-point if the Exception was caused by a unique constraint.
I'm wondering if there is some sort of recommended strategy for this situation?
Thanks
Pete
PS: I am using standard JDBC - not ORM.