sql - Should I check if a key exist before inserting or handle exception on insert? -


which operation more expensive -- issuing select query before insert, or handling exception during insert operation?

for example, assume want persist user request parameters param1(primary key & unique index), param2, param3 database table requirement display notification if duplicate key exists already. furthermore, assume real time scenario whole process isn't expected take more 500ms.

why recommended execute insert statement 3 params , handle insert exception cater duplicates? know throwing exception has cost -- cost of database query outweigh of throwing exception?

if insert 1,000,000 times , check first , insert, 1,000,000 checks , say, 957,512 inserts total of 1,957,512 actions against database. still have messaging user each of 42,488 records fail intial check.

if insert , throw exception have 1,000,000 actions against database , 42,488 exceptions handle.

so first way of doing business more work onteh database.


Comments