MySQL Update Row if Key Exists

Posted by on December 7, 2011 in Database, MySQL | 0 comments

Many times you have to do a query before you do a write action to a database because you have to see whether or not a row exists for the data you want to put in. If it does exist, you’d then do another query that was an update, otherwise you’d have to do an insert. Well if you want a quicker way, and you don’t need to use operators like “Update `column`+1”, then “REPLACE INTO” is the function for you. It works exactly like an insert, except that if the primary key already exists, it overwrites the existing row. Obviously you’ll want a primary key that’s stagnant and not an auto-incremented field, as you wouldn’t be passing the primary key to an auto-increment.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *