Advertisement
Beginner SQL Server, Merge Statement (Upsert)

What does the MERGE statement do in SQL Server, and why is it called an upsert operation?

Short answer

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…

Save SQL Server mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What is the difference between WHEN MATCHED and WHEN NOT MATCHED in a MERGE statement?
  • Can MERGE also handle deleting rows that no longer exist in the source?
Related topics