Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jan 082010
 

How to combine insert & update in a single SQL statement

Answer:

It is quite common to check if a given record already exist in database (check by primary key), insert it if not found, or update it if found.

It can be easily done using the MySQL's ON DUPLICATE KEY UPDATE statement

INSERT INTO `foo` (id, num) values (1, 0) 
                             ON DUPLICATE KEY UPDATE num = num + 1;

Reference: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html