Using ON DUPLICATE KEY UPDATE in MySQL
📖 Scenario: You are managing a small online store's product inventory. You want to add new products to the database, but if a product with the same product_id already exists, you want to update its price and stock instead of adding a duplicate entry.
🎯 Goal: Build a MySQL query that inserts a new product into the products table. If the product_id already exists, update the price and stock fields for that product.
📋 What You'll Learn
Create a
products table with columns product_id (primary key), name, price, and stock.Insert a product with specific values for
product_id, name, price, and stock.Add a query that uses
ON DUPLICATE KEY UPDATE to update price and stock if the product_id already exists.Ensure the final query correctly handles both insert and update scenarios.
💡 Why This Matters
🌍 Real World
Managing product inventory in an online store where products may be added or updated frequently.
💼 Career
Database administrators and backend developers often use ON DUPLICATE KEY UPDATE to efficiently handle insert-or-update operations.
Progress0 / 4 steps