Mysql INSERT … ON DUPLICATE KEY UPDATE

If you want to do some data loads in a Mysql DB regardless of insert or update statement you can use the INSERT … ON DUPLICATE KEY UPDATE request.

INSERT INTO test (firstname, lastname, skill)
      VALUES
      ('Alan', 'Cox', 98),
      ('Robert', 'Love', 85),
      ('Linus', 'Torvalds', 24),
      ('Rusty', 'Russell', 79)
ON DUPLICATE KEY UPDATE
     skill = VALUES(skill);

In this example, if the key is composed by firstname and lastname, when a duplicate key is detected, only the skill will be updated

You could find more informations on this statement here

Leave a Reply