Insert into a MySQL table or update if exists

Posted by
August 22, 2018

I we want to add a row to a database table, but if a row exists with the same unique key we want to update the row.

For example Let’s say the unique key is employee_id, and in my database there is a row with employee_id=1 , In that case we want to update that row with those values. Usually this gives an error. If I use ‘INSERT IGNORE’ it will ignore the error, but it still won’t update.

So to perform this we need

INSERT … ON DUPLICATE KEY UPDATE

INSERT INTO employees (employee_id, name, age) VALUES(1, "yourname", 20) ON DUPLICATE KEY UPDATE name="yourname", age=20

 

read more