Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

which is more efficient between catching or not SQL insert

 
Ranch Hand
Posts: 74
  • 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.
 
Bartender
Posts: 3225
34
IntelliJ IDE Oracle Spring Chrome Java
  • 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.
 
Master Rancher
Posts: 4668
49
  • 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.
 
Doe, a deer, a female deer. Ray, a pockeful of sun. Me, a name, I call my tiny ad ...
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic