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


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;


 Leave a Reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>