Journal Archives About Books Talks
til

TIL: Easy UPSERTS in MySQL

I've long loved upserts in MongoDB, but I suppose my desire to keep my SQL vanilla for Rails caused me to overlook easy upserts in MySQL using ON DUPLICATE KEY UPDATE:

INSERT INTO table (`user_id`, `some_expensive_count`) 
  VALUES (1, 333333)
  ON DUPLICATE KEY UPDATE `some_expensive_count` = 333333;

If the INSERT would cause a duplicate value in a PRIMARY KEY or UNIQUE index, an UPDATE is performed. Easy peasy.

# Posted on