How do I update if exists, insert if not (AKA "upsert" or "merge") in MySQL?

blub picture blub · Aug 2, 2009 · Viewed 58.6k times · Source

Is there an easy way to INSERT a row when it does not exist, or to UPDATE if it exists, using one MySQL query?

Answer

chaos picture chaos · Aug 2, 2009

Use INSERT ... ON DUPLICATE KEY UPDATE. For example:

INSERT INTO `usage`
(`thing_id`, `times_used`, `first_time_used`)
VALUES
(4815162342, 1, NOW())
ON DUPLICATE KEY UPDATE
`times_used` = `times_used` + 1