MySQL Insert or Update

Posted on Thursday May 26th, 2016

While working on a MySQL database recently I found I needed to insert a row if it didn't exist, or merely update the row if it was already present. I was glad to find out that this is possible as a single SQL command - as long as you know the primary key:

INSERT INTO table_name (id, col1, col2)
VALUES('pk123', 'foo', 1)
ON DUPLICATE KEY UPDATE col2 = col2 + 1;