A standard problem in applications is to insert a record if one doesn’t exist – or update if it does. In cases where the PRIMARY KEY is unknown this is usally solved by issuing a SELECT and then running either an INSERT or UPDATE if the record was found.
However, there seems to be at least three ways I know of that you can insert a record into a database even when a record already exists. Personally, I would rather drop the new insert request if one already exists, but then there might be cases where you would rather drop the record in the database and use the new one.
CREATE TABLE IF NOT EXISTS `table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`foo` int(10) unsigned NOT NULL,
`bar` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `row` (`foo`,`bar`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here are the three methods:
-
INSERT IGNORE INTO table (foo, bar) VALUES (2,3); -
INSERT INTO table (foo, bar) VALUES (2,3) ON DUPLICATE KEY UPDATE; -
REPLACE INTO table (foo, bar) VALUES (2,3);
At what times should each of these methods be used?
Can someone give some examples of correct usage scenarios?
INSERTshould be used when you just want to insert a new rowLets say you are storing log entries, you’ll want to log every event, use
INSERT.INSERT IGNOREshould be used when you just want there to be a specific key exists in the table, it doesn’t matter if it’s the current insert that creates it, or if it’s already present.Let’s say you have a table of phone-numbers and the number of uses, you find a new phone number that you are not sure exists in the table, but you want it to be there.
You use
INSERT IGNOREto make sure that it’s there.REPLACE INTOshould be used when you want to make sure that a specific key exists in the table, if it exists you’d like the new values to be used, instead of that present.You have another table with phone-numbers, this time you find a new number and a name to associate it with.
You use
REPLACE INTOto find and update a complete record, or just insert the new information.INSERT INTO ... ON DUPLICATE KEY UPDATE ...Please not that this is not an alternative method of writing
REPLACE INTO, the above should be used whenever you’d like to make sure that a specific key exists, but if it does update some of the columns, not all of them.For example if you are storing the numbers of visits from a certain IP, and the first page the user ever visited.
INSERT INTO visitors (ip,visits,first_page) VALUES (<ip>,1,<current_page>) ON DUPLICATE KEY visits = visits +1;