Bird
Raised Fist0
MySQLquery~20 mins

ON DUPLICATE KEY UPDATE in MySQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ON DUPLICATE KEY UPDATE Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Effect of ON DUPLICATE KEY UPDATE on existing row

Given the table users with columns id (primary key) and score, what will be the content of the table after executing the following query?

INSERT INTO users (id, score) VALUES (1, 10) ON DUPLICATE KEY UPDATE score = score + 5;

Assume the table initially contains: {id: 1, score: 20}.

A{id: 1, score: 10}
B{id: 1, score: 25}
C{id: 1, score: 15}
D{id: 1, score: 20}
Attempts:
2 left
💡 Hint

Think about what happens when the primary key already exists.

🧠 Conceptual
intermediate
2:00remaining
Behavior when no duplicate key exists

What happens when you run this query on a table where the primary key does not exist yet?

INSERT INTO products (product_id, quantity) VALUES (5, 100) ON DUPLICATE KEY UPDATE quantity = quantity + 10;
AThe query fails with a duplicate key error.
BThe existing row with product_id 5 is updated to quantity 110.
CA new row with product_id 5 and quantity 100 is inserted.
DNo changes happen to the table.
Attempts:
2 left
💡 Hint

Consider what happens if the key is not found.

📝 Syntax
advanced
2:00remaining
Correct syntax for ON DUPLICATE KEY UPDATE

Which of the following queries is syntactically correct in MySQL?

INSERT INTO inventory (item_id, stock) VALUES (3, 50) ON DUPLICATE KEY UPDATE stock = stock - 1;
AINSERT INTO inventory (item_id, stock) VALUES (3, 50) ON DUPLICATE UPDATE stock = stock - 1;
BINSERT INTO inventory (item_id, stock) VALUES (3, 50) DUPLICATE KEY UPDATE stock = stock - 1;
CINSERT INTO inventory (item_id, stock) VALUES (3, 50) ON DUPLICATE KEY SET stock = stock - 1;
DINSERT INTO inventory (item_id, stock) VALUES (3, 50) ON DUPLICATE KEY UPDATE stock = stock - 1;
Attempts:
2 left
💡 Hint

Check the exact keywords and their order.

❓ optimization
advanced
2:00remaining
Optimizing multiple row inserts with ON DUPLICATE KEY UPDATE

You want to insert multiple rows into a table and update existing rows if keys duplicate. Which query is the most efficient?

AUse a single multi-row INSERT ... ON DUPLICATE KEY UPDATE query with all rows.
BRun multiple single-row INSERT ... ON DUPLICATE KEY UPDATE queries, one per row.
CDelete all rows first, then insert all rows without ON DUPLICATE KEY UPDATE.
DUse UPDATE queries for existing rows and INSERT for new rows separately.
Attempts:
2 left
💡 Hint

Think about reducing the number of queries sent to the database.

🔧 Debug
expert
3:00remaining
Diagnosing unexpected behavior with ON DUPLICATE KEY UPDATE

Consider this table orders with a unique key on order_number. You run:

INSERT INTO orders (order_number, status) VALUES ('A123', 'pending') ON DUPLICATE KEY UPDATE status = 'pending';

But the status does not update when you expect it to. What is the most likely cause?

AThe existing row already has status 'pending', so no change occurs.
BThe query syntax is incorrect and causes a silent failure.
CThe database does not support ON DUPLICATE KEY UPDATE.
DThe unique key is not on order_number, so no duplicate is detected.
Attempts:
2 left
💡 Hint

Think about what happens if the update sets the same value as before.

Practice

(1/5)
1. What does the ON DUPLICATE KEY UPDATE clause do in a MySQL INSERT statement?
easy
A. It deletes rows with duplicate keys before inserting new ones.
B. It updates existing rows if a duplicate key is found during insert.
C. It ignores the insert if a duplicate key exists.
D. It creates a new table when a duplicate key is found.

Solution

  1. Step 1: Understand the purpose of ON DUPLICATE KEY UPDATE

    This clause allows an INSERT statement to update existing rows if a duplicate key (like a primary key) is found instead of causing an error.
  2. 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.
  3. Final Answer:

    It updates existing rows if a duplicate key is found during insert. -> Option B
  4. Quick Check:

    ON DUPLICATE KEY UPDATE = update on duplicate [OK]
Hint: It updates rows when duplicate keys appear during insert [OK]
Common Mistakes:
  • Thinking it deletes rows instead of updating
  • Assuming it ignores duplicates silently
  • Confusing it with creating new tables
2. Which of the following is the correct syntax to use ON DUPLICATE KEY UPDATE in MySQL?
easy
A. INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE KEY UPDATE val = 'b';
B. INSERT INTO table (id, val) VALUES (1, 'a') DUPLICATE KEY UPDATE val = 'b';
C. INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE UPDATE val = 'b';
D. INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE KEY SET val = 'b';

Solution

  1. Step 1: Recall the correct syntax format

    The correct syntax is INSERT INTO ... VALUES (...) ON DUPLICATE KEY UPDATE column = value;
  2. 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.
  3. Final Answer:

    INSERT INTO table (id, val) VALUES (1, 'a') ON DUPLICATE KEY UPDATE val = 'b'; -> Option A
  4. Quick Check:

    Correct syntax includes 'ON DUPLICATE KEY UPDATE' [OK]
Hint: Remember full phrase: ON DUPLICATE KEY UPDATE [OK]
Common Mistakes:
  • Omitting the word KEY
  • Using UPDATE without ON DUPLICATE KEY
  • Replacing UPDATE with SET
3. Given the table 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;
medium
A. A new row with id=1 and points=20 is inserted.
B. The existing row with id=1 is updated to points=5.
C. The existing row with id=1 is updated to points=15.
D. The query causes a duplicate key error.

Solution

  1. Step 1: Identify duplicate key and update action

    The id 1 already exists, so the ON DUPLICATE KEY UPDATE clause triggers. It updates points by adding 5 to the existing value.
  2. Step 2: Calculate updated points value

    Existing points = 10, so new points = 10 + 5 = 15.
  3. Final Answer:

    The existing row with id=1 is updated to points=15. -> Option C
  4. Quick Check:

    points = 10 + 5 = 15 [OK]
Hint: Update adds to existing value on duplicate key [OK]
Common Mistakes:
  • Thinking it inserts a new row instead of updating
  • Assuming points become 20 instead of adding 5
  • Expecting an error on duplicate key
4. What is wrong with this query?
INSERT INTO products (id, stock) VALUES (5, 10) ON DUPLICATE KEY UPDATE stock = stock + 1,;
medium
A. The VALUES keyword is not allowed with ON DUPLICATE KEY UPDATE.
B. The ON DUPLICATE KEY UPDATE clause is missing a column.
C. The stock column cannot be updated this way.
D. The comma before the semicolon causes a syntax error.

Solution

  1. 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.
  2. Step 2: Identify correct syntax rules

    There should be no trailing comma after the last update assignment.
  3. Final Answer:

    The comma before the semicolon causes a syntax error. -> Option D
  4. Quick Check:

    Trailing comma in UPDATE clause = syntax error [OK]
Hint: No trailing comma after last update assignment [OK]
Common Mistakes:
  • Leaving a comma after last column update
  • Confusing VALUES usage with ON DUPLICATE KEY UPDATE
  • Thinking stock column can't be updated
5. You want to insert a new user or update their score only if the new score is higher than the existing one. Which query correctly uses ON DUPLICATE KEY UPDATE for this?
hard
A. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = IF(score < VALUES(score), VALUES(score), score);
B. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = VALUES(score);
C. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = score + VALUES(score);
D. INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = score - VALUES(score);

Solution

  1. Step 1: Understand the requirement

    We want to update the score only if the new score is greater than the existing score.
  2. 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); uses IF to 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.
  3. Final Answer:

    INSERT INTO users (id, score) VALUES (2, 50) ON DUPLICATE KEY UPDATE score = IF(score < VALUES(score), VALUES(score), score); -> Option A
  4. Quick Check:

    Use IF to update only if new score is higher [OK]
Hint: Use IF(condition, new, old) to update conditionally [OK]
Common Mistakes:
  • Always overwriting score without condition
  • Adding scores instead of comparing
  • Subtracting scores mistakenly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard