This helps you add a new row or update an existing row if a duplicate key is found. It saves time by doing both in one command.
ON DUPLICATE KEY UPDATE in MySQL
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...) ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2, ...;
The duplicate key is usually a PRIMARY KEY or UNIQUE index.
You can update one or more columns after the duplicate key is found.
INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30) ON DUPLICATE KEY UPDATE age = VALUES(age);
INSERT INTO products (sku, price) VALUES ('A123', 10.99) ON DUPLICATE KEY UPDATE price = VALUES(price);
INSERT INTO inventory (item_id, quantity) VALUES (5, 100) ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity);
This creates a users table, inserts Alice with age 25, then tries to insert Alice again with age 30. Because id=1 exists, it updates age to 30. Finally, it selects Alice's record.
CREATE TABLE IF NOT EXISTS users ( id INT PRIMARY KEY, name VARCHAR(50), age INT ); INSERT INTO users (id, name, age) VALUES (1, 'Alice', 25); INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30) ON DUPLICATE KEY UPDATE age = VALUES(age); SELECT * FROM users WHERE id = 1;
Make sure the table has a PRIMARY KEY or UNIQUE index for this to work.
You can use VALUES(column) in the UPDATE part to refer to the new value.
This is a quick way to avoid separate SELECT checks before INSERT or UPDATE.
Use ON DUPLICATE KEY UPDATE to insert or update in one step.
It works when a duplicate key (like PRIMARY KEY) is found.
You can update one or more columns with new values or calculations.
Practice
ON DUPLICATE KEY UPDATE clause do in a MySQL INSERT statement?Solution
Step 1: Understand the purpose of ON DUPLICATE KEY UPDATE
This clause allows anINSERTstatement to update existing rows if a duplicate key (like a primary key) is found instead of causing an error.Step 2: Compare options with this behavior
Only It updates existing rows if a duplicate key is found during insert. correctly describes this behavior. The other options describe different actions that are not what this clause does.Final Answer:
It updates existing rows if a duplicate key is found during insert. -> Option BQuick Check:
ON DUPLICATE KEY UPDATE = update on duplicate [OK]
- Thinking it deletes rows instead of updating
- Assuming it ignores duplicates silently
- Confusing it with creating new tables
ON DUPLICATE KEY UPDATE in MySQL?Solution
Step 1: Recall the correct syntax format
The correct syntax isINSERT INTO ... VALUES (...) ON DUPLICATE KEY UPDATE column = value;Step 2: Match options with correct syntax
Only INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE KEY UPDATE val = 'b'; matches the exact syntax. The other options have incorrect keywords or missing parts.Final Answer:
INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE KEY UPDATE val = 'b'; -> Option AQuick Check:
Correct syntax includes 'ON DUPLICATE KEY UPDATE' [OK]
- Omitting the word KEY
- Using UPDATE without ON DUPLICATE KEY
- Replacing UPDATE with SET
users(id INT PRIMARY KEY, name VARCHAR(20), points INT) with data:(1, 'Alice', 10)What will be the result after running?
INSERT INTO users (id, name, points) VALUES (1, 'Alice', 20) ON DUPLICATE KEY UPDATE points = points + 5;
Solution
Step 1: Identify duplicate key and update action
Theid1 already exists, so theON DUPLICATE KEY UPDATEclause triggers. It updatespointsby adding 5 to the existing value.Step 2: Calculate updated points value
Existing points = 10, so new points = 10 + 5 = 15.Final Answer:
The existing row with id=1 is updated to points=15. -> Option CQuick Check:
points = 10 + 5 = 15 [OK]
- Thinking it inserts a new row instead of updating
- Assuming points become 20 instead of adding 5
- Expecting an error on duplicate key
INSERT INTO products (id, stock) VALUES (5, 10) ON DUPLICATE KEY UPDATE stock = stock + 1,;
Solution
Step 1: Check syntax of ON DUPLICATE KEY UPDATE clause
The clause ends with a comma before the semicolon, which is invalid syntax in SQL.Step 2: Identify correct syntax rules
There should be no trailing comma after the last update assignment.Final Answer:
The comma before the semicolon causes a syntax error. -> Option DQuick Check:
Trailing comma in UPDATE clause = syntax error [OK]
- Leaving a comma after last column update
- Confusing VALUES usage with ON DUPLICATE KEY UPDATE
- Thinking stock column can't be updated
ON DUPLICATE KEY UPDATE for this?Solution
Step 1: Understand the requirement
We want to update the score only if the new score is greater than the existing score.Step 2: Analyze each option's update logic
INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = VALUES(score); always replaces the score, ignoring if it's higher or not. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = IF(score < VALUES(score), VALUES(score), score); usesIFto update only if new score is higher. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = score + VALUES(score); adds scores, which is not the requirement. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = score - VALUES(score); subtracts scores, which is incorrect.Final Answer:
INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = IF(score < VALUES(score), VALUES(score), score); -> Option AQuick Check:
Use IF to update only if new score is higher [OK]
- Always overwriting score without condition
- Adding scores instead of comparing
- Subtracting scores mistakenly
Ready to prove it?
Pass the test and this pattern moves unknown
