SQL Server › Merge Statement (Upsert)
What does the MERGE statement do in SQL Server, and why is it called an upsert operation?
BeginnerAnswer
The MERGE statement lets you compare a source set of data against a target table and, in a single statement, insert new rows that do not yet exist, update existing rows that have changed, and optionally delete rows that no longer appear in the source, which is why it is commonly called an upsert since it combines update and insert logic together.
MERGE INTO Products AS target
USING StagingProducts AS source
ON target.ProductId = source.ProductId
WHEN MATCHED THEN UPDATE SET target.Price = source.Price
WHEN NOT MATCHED THEN INSERT (ProductId, Price) VALUES (source.ProductId, source.Price);Real-world example A nightly product synchronization job uses MERGE to update prices for existing products and insert brand new products from a staging table, all in a single, clean statement instead of writing separate insert and update logic.