Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

which is more efficient between catching or not SQL insert

 
Matt Taylor
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an application that inserts single data in the MYSQL db. However, if the data exists, I will not update/insert the record anymore; just discard the data
Do you think which is efficient between the two:

1. Directly execute insert statement then just put a catch clause to catch duplicate primary key exception
2. Execute a select statement first to find if primary key exists in DB then if not, execute insert.

I think option 2 is more cleaner but I want to know which is more efficient.
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3165
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sure MySQL supports on duplicate key update clause where in it updates the rows whenever it finds a duplicate key.

Now how you handle - i.e whether update or discard the update depends on your requirement. If its required to track/record the update then you would record it.
 
Dave Tolls
Ranch Hand
Posts: 2095
15
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matt Taylor wrote:...
2. Execute a select statement first to find if primary key exists in DB then if not, execute insert.

I think option 2 is more cleaner but I want to know which is more efficient.


If this is a threaded environment, option 2 still requires you to check for the primary key exception.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic