INSERT ON DUPLICATE KEY UPDATE

suggest change
INSERT INTO `table_name` 
    (`index_field`, `other_field_1`, `other_field_2`) 
    VALUES 
    ('index_value', 'insert_value', 'other_value') 
    ON DUPLICATE KEY UPDATE 
        `other_field_1` = 'update_value',
        `other_field_2` = VALUES(`other_field_2`);

This will INSERT into table_name the specified values, but if the unique key already exists, it will update the other_field_1 to have a new value.

Sometimes, when updating on duplicate key it comes in handy to use VALUES() in order to access the original value that was passed to the INSERT instead of setting the value directly. This way, you can set different values by using INSERT and UPDATE. See the example above where other_field_1 is set to insert_value on INSERT or to update_value on UPDATE while other_field_2 is always set to other_value.

IODKU does nothing special unless the table has a PRIMARY KEY or UNIQUE key that the new row clashes with. That key can be one column or several. VALUES(col) inside the UPDATE is deprecated as of MySQL 8.0.20. Prefer an alias: INSERT INTO t (...) VALUES (...) AS new ON DUPLICATE KEY UPDATE col = new.col.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents