views:

82

answers:

2

I want to update a record which may or may not be present in a table. If it is not present in the database then it will be inserted.

To prevent from select I am using UPDATE statement first and checking affected_rows > 0 if not then I am inserting this record into the table.

I was wondering if there is a better way to do this?

+3  A: 

Use Replace instead of Insert.

http://dev.mysql.com/doc/refman/5.0/en/replace.html

Femaref
+4  A: 

You could use INSERT ... ON DUPLICATE KEY UPDATE syntax:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html


The difference between this and REPLACE (Femaref's answer) is that REPLACE will delete the old row and then insert a new row if a key is duplicated, while this will update the existing row.

NullUserException
What if database goes down during replace process?
Jason
@NullUserException this query wont work for auto generated number isn't?
Jason
@Jason Yes it will. As long as there is a duplicate key it will do `UPDATE`
NullUserException
I just checked it, I have to add unique index on column(s) in order to find duplicates. Is it OK if I do not use primary key?
Jason
@Jason It depends on how you determine whether or not two records are "duplicates." You can have two people called "John Smith" and they are not the same person.
NullUserException