Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should check for duplicate or catch exception from database?

When we program with database (for example in Java and MySql), should we check for duplicate entry before inserting, or should we just insert and catch the duplicate exception to raise alert to users ?

In my opinion, if we do the check, and if there is no duplicate entry, we insert the entry, and the database engine itself checks for duplicate primary key again. It sounds a waste of time.

How do you think?

like image 346
hirikarate Avatar asked Dec 21 '22 08:12

hirikarate


1 Answers

For you to check client side(in your program) if there is a duplicate key, it would require querying the database. Since the insert query will return an error if there is already a record existing with the same PK, it is not necessary to perform this check before the insert statement is sent.
You can insert, catch the exception/error code (i'm not sure if it will give an exception in java, or return an error code) and then alert the user.

EDIT -
If there are many users using the same database, the main issue if you check and then insert will be that someone else can insert the same key after you checked but before you insert. IF you would like to do it this way, you would need to use transactions - the check and insert must both happen in the same transaction. You can read up on MySQL transactions here.

like image 68
Jan S Avatar answered Dec 24 '22 01:12

Jan S