SQL
Perform Atomic Upsert Operations with MySQL
Atomically insert new records or update existing ones in a single SQL query using MySQL's 'INSERT ... ON DUPLICATE KEY UPDATE' syntax.
INSERT INTO products (product_id, product_name, price, stock)
VALUES (101, 'Wireless Earbuds', 79.99, 150)
ON DUPLICATE KEY UPDATE
product_name = VALUES(product_name),
price = VALUES(price),
stock = VALUES(stock);
-- Example for PostgreSQL (INSERT ... ON CONFLICT DO UPDATE)
-- INSERT INTO products (product_id, product_name, price, stock)
-- VALUES (101, 'Wireless Earbuds', 79.99, 150)
-- ON CONFLICT (product_id) DO UPDATE SET
-- product_name = EXCLUDED.product_name,
-- price = EXCLUDED.price,
-- stock = EXCLUDED.stock;
How it works: This snippet demonstrates the 'upsert' pattern for MySQL, which allows you to either insert a new record or update an existing one if a unique key (like `product_id`) already exists. The `ON DUPLICATE KEY UPDATE` clause specifies which columns to update with the new `VALUES()` provided in the `INSERT` statement. This ensures data integrity and simplifies logic for managing records that might already exist, acting as an atomic operation. A commented example for PostgreSQL's `ON CONFLICT DO UPDATE` is also included for reference.