0
0
MySQLquery~3 mins

Why ON DUPLICATE KEY UPDATE in MySQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix duplicates and update data with just one simple command?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
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;
After
INSERT INTO products (id, stock) VALUES (123, 10)
ON DUPLICATE KEY UPDATE stock = stock + 10;
What It Enables

This lets you quickly and safely add or update records in one step, making your database work smarter and faster.

Real Life Example

Online stores use this to update product stock instantly when new shipments arrive, ensuring customers always see the correct availability without delays or errors.

Key Takeaways

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.