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.