Click here to Skip to main content
15,912,507 members
Articles / Programming Languages / SQL

Mysql: Insert or Update in One SQL Statement

Rate me:
Please Sign up or sign in to vote.
2.54/5 (5 votes)
6 May 2015CPOL 11.2K   1   2
MySQL: insert or update in one SQL statement

I must say, I really wish I knew about this technique years ago ?before I started using frameworks to do a lot of my development. The effort that was wasted in building separate code and separate logic to deal with inserts vs updates, when all of this time, there is a nice and simple feature built-in to Mysql that does this for us?.

The process is quite straight forward, when I run a standard INSERT statement with Mysql, I can provide additional properties for dealing with DUPLICATE KEY, e.g. the record already exists.

Here is an example:

SQL
INSERT INTO `table` (`name`, `created`, `modified`)
VALUES ('Jamie', NOW(), NOW())
ON DUPLICATE KEY
UPDATE `name` = 'Jamie', `modified` = NOW()

Notice how in the UPDATE statement I'm only updating the name and modified date.

Another nice example can be used for keeping track of the number of times a tag is used.  Imagine you have a table with a list of tags and their associated count. You can leverage the above functionality to increase the count each time the tag is used again:

SQL
INSERT INTO `tags` (`tag`, `count`, `created`, `modified`)
VALUES ('mysql', 1, NOW(), NOW())
ON DUPLICATE KEY
UPDATE `count` = `count` + 1, `modified` = NOW()

That's it! No more need to right functionality like:

SQL
if ($id == 0) {
// do insert
} else {
// do update
}

For my information, visit Mysql Documentation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
SuggestionLastUpdate Pin
Silvério Miranda7-May-15 9:49
Silvério Miranda7-May-15 9:49 
Use TIMESTAMP for save lastupdate date of field like :

SQL
CREATE TABLE t1 (
  LastUpdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);


You dont need to update that field, just read

Smile | :)
QuestionUseful info Pin
User 95447147-May-15 9:06
professionalUser 95447147-May-15 9:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.