SQL

Upsert Data into a Table (Insert or Update)

Perform an upsert operation to either insert a new record or update an existing one if a unique constraint is violated, ensuring data integrity.

INSERT INTO products (product_id, product_name, price, stock_quantity)
VALUES (101, 'New Gadget', 29.99, 100)
ON CONFLICT (product_id) DO UPDATE SET
  product_name = EXCLUDED.product_name,
  price = EXCLUDED.price,
  stock_quantity = products.stock_quantity + EXCLUDED.stock_quantity; -- Add new stock to existing
How it works: This snippet performs an 'upsert' operation, meaning it will either `INSERT` a new row or `UPDATE` an existing one if a unique constraint is violated. The `ON CONFLICT (product_id)` clause specifies that if a record with the same `product_id` already exists, an update should occur instead of an error. `DO UPDATE SET` then defines which columns to update; `EXCLUDED.column_name` refers to the values that would have been inserted. For MySQL, a similar functionality is achieved using `INSERT INTO ... VALUES (...) ON DUPLICATE KEY UPDATE ...`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs