ON DUPLICATE KEY UPDATE in MySQL - Time & Space Complexity
When using ON DUPLICATE KEY UPDATE in MySQL, it's important to understand how the time to run the query changes as the data grows.
We want to know how the database handles inserting or updating rows when keys conflict.
Analyze the time complexity of the following query.
INSERT INTO users (id, name, score)
VALUES (1, 'Alice', 10)
ON DUPLICATE KEY UPDATE
score = score + 10;
This query tries to insert a user. If the user ID already exists, it updates the score instead.
Look for operations that repeat or take time depending on data size.
- Primary operation: Checking if the key (user ID) exists in the table.
- How many times: This check happens once per query execution.
The time to check if the key exists depends on how MySQL finds the key in the index.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-4 steps to find key |
| 100 | About 7 steps to find key |
| 1000 | About 10 steps to find key |
Pattern observation: The search steps grow slowly as data grows, because the database uses an index tree to find keys efficiently.
Time Complexity: O(log n)
This means the time to insert or update grows slowly as the table gets bigger, thanks to efficient key lookup.
[X] Wrong: "The query always scans the whole table to find duplicates."
[OK] Correct: The database uses indexes to quickly find keys, so it does not check every row.
Understanding how ON DUPLICATE KEY UPDATE works helps you explain how databases handle conflicts efficiently, a useful skill in many real-world projects.
"What if the table has no index on the key column? How would the time complexity change?"
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
