Create if an entry if it doesn’t exist, otherwise update?

A lot of developers still execute a query to check if a field is present in a table and then execute an insert or update query according to the result of the first query.
Try using the ON DUPLICATE KEY syntax, this is a lot faster and better then executing 2 queries. More info can be found here

INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;

if you want to keep the same value for c you can do an update with the same value

INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=6;

the difference between ‘replace’ and ‘on duplicate key’:

replace: inserts, or deletes and inserts

on duplicate key: inserts or updates

if your table doesn’t have a primary key or unique key, the replace doesn’t make any sense.

You can also use the VALUES function to avoid having to specify the actual values twice. E.g. instead of

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=6;

you can use

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(c);

Where VALUES(c) will evaluate to the value specified prevously (6).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)