Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE record if present; else INSERT

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?

like image 230
Jason Avatar asked Jun 30 '26 10:06

Jason


1 Answers

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.

like image 146
NullUserException Avatar answered Jul 03 '26 03:07

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!