MySQL - on duplicate key update

If you've ever built an application that interacts with a database and allows users to edit data, or one that migrates data from one system to another you've probably written code like this:

  1. // $id would have been set based on some other operation above.
  2. // I'm setting it here for clarity.
  3. $id = 1;
  4.  
  5. $result = mysql_query("SELECT id FROM table_name WHERE id = $id");
  6.  
  7. if(mysql_num_rows() == 0){
  8.      // Zero results, the record doesn't exist, add it.
  9.      mysql_query("INSERT INTO table_name (id,a,b) VALUES ($id,2,3)");
  10. }
  11. else{
  12.      // The record exists, update it.
  13.      mysql_query("UPDATE table_name SET a = 1, b = 2 WHERE id = $id");
  14. }

Well, thanks to the ON DUPLICATE KEY UPDATE option in MySQL this can be condensed to the following:

  1. $result = mysql_query("INSERT INTO table_name SET id = $id, a = 2, b = 3
  2. 					 ON DUPLICATE KEY UPDATE
  3. 					 a = 2, c = 3");

Notes: