2010
05.21
05.21
When I was trying to keep some data from a table A mirrored in an other table B, I was confronted with the issue: what to do with rows that are already present in table B. Do I have to check if they are already present and then do an UPDATE instead of an INSERT? There must be an easier way. And there is, INSERT … ON DUPLICATE KEY UPDATE.
The syntax is very straightforward:
INSERT INTO table_b (id,title,body) VALUES (1,'Title','Body') ON DUPLICATE KEY UPDATE title=VALUES(title), body=VALUES(body);
In the example above, if table_b already has a row with the unique id value 1, this row is being updated with the new title and body.
It’s as easy as that, not two queries and if..else statement, but just one nice query.