How to Perform an UPSERT so that I can use both new and old values in update part

As mentioned in my comment, you don’t have to do the subselect to reference to the row that’s causing ON DUPLICATE KEY to fire. So, in your example you can use the following:

INSERT INTO `item`
(`item_name`, items_in_stock)
VALUES( 'A', 27)
ON DUPLICATE KEY UPDATE
`new_items_count` = `new_items_count` + 27

Remember that most things are really simple, if you catch yourself overcomplicating something that should be simple then you are most likely doing it the wrong way 🙂

Leave a Comment