What if you could fix duplicates and update data with just one simple command?
Why ON DUPLICATE KEY UPDATE in MySQL? - Purpose & Use Cases
Imagine you have a list of products and their stock counts in a spreadsheet. Every time you get new stock, you have to check if the product is already listed. If it is, you update the stock count; if not, you add a new row. Doing this by hand for hundreds of products is tiring and slow.
Manually checking each product wastes time and causes mistakes like adding duplicates or forgetting to update counts. It's easy to lose track or overwrite the wrong data, especially when many updates happen at once.
The ON DUPLICATE KEY UPDATE feature in MySQL lets you try inserting new data, but if the product already exists (based on a unique key), it automatically updates the existing record instead. This saves time and avoids errors by handling both insert and update in one simple command.
IF EXISTS (SELECT * FROM products WHERE id=123) THEN UPDATE products SET stock=stock+10 WHERE id=123; ELSE INSERT INTO products (id, stock) VALUES (123, 10); END IF;
INSERT INTO products (id, stock) VALUES (123, 10) ON DUPLICATE KEY UPDATE stock = stock + 10;
This lets you quickly and safely add or update records in one step, making your database work smarter and faster.
Online stores use this to update product stock instantly when new shipments arrive, ensuring customers always see the correct availability without delays or errors.
Manually updating or inserting data is slow and error-prone.
ON DUPLICATE KEY UPDATE combines insert and update into one easy command.
This keeps your data accurate and your work efficient.
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
