2

When adding a row to a table, but first checking to see if it exists first Which would be the most efficient way of handling this?

Would it be a case of query to see if it exist, if not then insert.

Or using on duplicate?

Or simply replace (Would this work, if the row did not exist)?

Thanks

Rory Standley
  • 1,130
  • 2
  • 20
  • 36
  • Define the criteria for *checking to see if it exists*. – Salman A Mar 12 '12 at 10:24
  • possible duplicate of [How to 'insert if not exists' in MySQL?](http://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql) – John Woo Mar 12 '12 at 10:26
  • Maybe, I didnt explain very well sorry. I was kind of meaning how best to go about it would checking to see it exists first be the best route – Rory Standley Mar 12 '12 at 10:27

3 Answers3

3

I think this is the fastest way in MySQL:

REPLACE into table (col1, col2) values(1, 'ABC')

EDIT:

MySQL will delete the row if it does exist and insert a new one.

juergen d
  • 186,950
  • 30
  • 261
  • 325
2

I think you need INSERT IGNORE see this or INSERT ON DUPLICATE KEY UPDATE

dotoree
  • 2,935
  • 1
  • 21
  • 28
1

depends what you mean by 'exists' if there is a unique field you can check against such as 'email' or 'login' then you can just try the insert and mysql raise error if exists, otherwise you'd do the replace as juergen d just suggested.

NB: don't use replace if you wanted your timestamps for any reason (such as if they're used in encrypted passwords or salt

TomDunning
  • 4,432
  • 1
  • 22
  • 31