SQL

Upsert (Insert or Update) Data in MySQL

Implement an 'upsert' operation in MySQL to either insert new records or update existing ones if a key conflict occurs, streamlining data management.

INSERT INTO 
  products (product_name, description, price)
VALUES 
  ('New Gadget', 'A cool new device', 299.99)
ON DUPLICATE KEY UPDATE 
  description = VALUES(description),
  price = VALUES(price);
How it works: This snippet demonstrates an "upsert" operation, a common pattern where you want to insert a row if it doesn't exist, or update it if it does. This specific syntax is for MySQL, which requires a `UNIQUE` key (e.g., `product_name`) to trigger the `ON DUPLICATE KEY UPDATE` clause. If a row with the given `product_name` already exists, its `description` and `price` will be updated; otherwise, a new row will be inserted.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs