![]() |
VOOZH | about |
This statement is used to handle duplicate entries efficiently by combining insert and update operations in a single query. It behaves like a normal INSERT until a duplicate key is encountered.
Syntax:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON DUPLICATE KEY UPDATE
column1 = value1,
column2 = value2;The ON DUPLICATE KEY UPDATE clause specifies the columns to update when a duplicate key is detected.
It allows inserting new records while automatically updating existing ones when a duplicate key occurs. It ensures efficient data handling by combining insert and update operations in a single query.
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);INSERT INTO employees (name)
VALUES ('Alice'), ('Bob'), ('Charlie');SELECT id, name FROM employees;Output:
INSERT INTO employees (name)
VALUES ('David')
ON DUPLICATE KEY UPDATE name = 'David';Since there is no duplicate key, MySQL inserts a new row.
SELECT id, name FROM employees;Output:
INSERT INTO employees (id, name)
VALUES (4, 'Eve')
ON DUPLICATE KEY UPDATE name = 'Eve';Since id = 4 already exists, MySQL updates the existing row instead of inserting a new one.
Output:
2 row(s) affectedSELECT id, name FROM employees;Output:
Follow these guidelines to safely and effectively use INSERT ON DUPLICATE KEY UPDATE.