Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Performance - Better to Insert and Raise Exception or Check exists?

I'm considering an optimisation in a particularly heavy part of my code. It's task is to insert statistical data into a table. This data is being hit a fair amount by other programs. Otherwise I would consider using SQL Bulk inserts etc.

So my question is...

Is it ok to try and insert some data knowing that it might (not too often) throw a SqlException for a duplicate row?

Is the performance hit of an exception worse than checking each row prior to insertion?

like image 338
Andrew Harry Avatar asked Feb 16 '09 07:02

Andrew Harry


People also ask

How can you improve the performance of an insert query?

To optimize insert speed, combine many small operations into a single large operation. Ideally, you make a single connection, send the data for many new rows at once, and delay all index updates and consistency checking until the very end.

Which is faster select or insert in SQL?

SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage. However, providing the query hint to lock the entire destination table, the two statements perform exactly the same.

How do you handle exceptions in SQL?

To handle exception in Sql Server we have TRY.. CATCH blocks. We put T-SQL statements in TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY block then the control will automatically jump to the corresponding CATCH blocks.

Can we use try catch in SQL function?

A TRY... CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection. A TRY block must be immediately followed by an associated CATCH block. Including any other statements between the END TRY and BEGIN CATCH statements generates a syntax error.


1 Answers

First, my advice is to err on the side of correctness, not speed. When you finish your project and profiling shows that you lose significant time checking that rows exist before inserting them, only then optimize it.

Second, I think there's syntax for inserting and skipping if there are duplicates in all RDBMS, so this shouldn't be a problem in the first place. I try to avoid exceptions as part of the normal application flow and leave them for truly exceptional cases. That is, don't count on exceptions in the DB to work around logic in your code. Maintain as much consistency on your end (code), and let DB exceptions indicate only true bugs.

like image 157
Assaf Lavie Avatar answered Nov 15 '22 05:11

Assaf Lavie