Careeroza
UPSERT & MERGE
Insert or Update
An upsert inserts a row, or updates it if a row with the same key already exists, in one atomic statement.
Example
SQLite and PostgreSQL use ON CONFLICT:
INSERT INTO Products (ProductID, ProductName, Category, Price, Stock)
VALUES (2, 'Green Tea 100 bags', 'Beverages', 6.75, 50)
ON CONFLICT (ProductID) DO UPDATE SET Stock = Stock + excluded.Stock;
SELECT * FROM Products WHERE ProductID = 2;Result: 1 row
| ProductID | ProductName | Category | Price | Stock |
|---|---|---|---|---|
| 2 | Green Tea 100 bags | Beverages | 6.75 | 350 |
excluded refers to the row you tried to insert.
MySQL and SQL Server
-- MySQL 8.0.19+ (older versions use VALUES(Stock), now deprecated)
INSERT INTO Products (ProductID, ProductName, Category, Price, Stock)
VALUES (2, 'Green Tea 100 bags', 'Beverages', 6.75, 50) AS new
ON DUPLICATE KEY UPDATE Stock = Products.Stock + new.Stock;
-- SQL Server / Oracle / PostgreSQL 15+: MERGE
MERGE INTO Products AS target
USING (VALUES (2, 'Green Tea 100 bags', 'Beverages', 6.75, 50))
AS src (ProductID, ProductName, Category, Price, Stock)
ON target.ProductID = src.ProductID
WHEN MATCHED THEN
UPDATE SET Stock = target.Stock + src.Stock
WHEN NOT MATCHED THEN
INSERT (ProductID, ProductName, Category, Price, Stock)
VALUES (src.ProductID, src.ProductName, src.Category, src.Price, src.Stock);