SQL
Perform an UPSERT Operation with ON DUPLICATE KEY UPDATE (MySQL)
Master the MySQL UPSERT pattern to either insert new rows or update existing ones if a unique key conflict occurs, ensuring data integrity efficiently.
INSERT INTO products (product_id, product_name, price, last_updated)
VALUES ('P001', 'Laptop Pro', 1200.00, NOW())
ON DUPLICATE KEY UPDATE
product_name = VALUES(product_name),
price = VALUES(price),
last_updated = NOW();
How it works: This SQL snippet demonstrates an "UPSERT" operation using MySQL's `ON DUPLICATE KEY UPDATE` clause. If a row with the specified `product_id` (assuming it's a primary or unique key) already exists, its `product_name`, `price`, and `last_updated` columns are updated with the new values. Otherwise, a new row is inserted, efficiently managing data updates or insertions.