SQL Server · Advanced Querying

MERGE Statement

MERGE compares a source with a target and inserts, updates or deletes rows in one statement — ideal for syncing imported data.

Intermediate 5 min Lesson 31 of 44Examples run on SQL Server 2022 and Azure SQL Database.
Before you start:UPDATEINSERT
0/44 in SQL Server
On this page · 5 min · Intermediate

Learning objectives#

  • Write a MERGE with all three actions
  • Log what happened with OUTPUT $action
  • Avoid duplicate-match errors
  • Know when separate statements are better

Explanation#

MERGE target USING source ON match condition, then WHEN MATCHED (update or delete), WHEN NOT MATCHED BY TARGET (insert) and WHEN NOT MATCHED BY SOURCE (rows in the target that are missing from the source). The statement must end with a semicolon.

The source must have at most one row per target row; otherwise MERGE fails with “attempted to UPDATE or DELETE the same row more than once”. Deduplicate the source first.

OUTPUT $action, inserted.*, deleted.* reports exactly what changed — useful for audit logs.

Under concurrent load, add WITH (HOLDLOCK) on the target to avoid race conditions, or use separate UPDATE and INSERT statements in a transaction, which many teams find easier to read and tune.

Step-by-step screens#

Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.

Loading pictures…

Code example: Sync product prices from a supplier file#

SQLSync product prices from a supplier file Illustrative
-- Staging.Products was loaded from the supplier's CSV
MERGE dbo.Products WITH (HOLDLOCK) AS t
USING Staging.Products AS s
    ON t.Sku = s.Sku
WHEN MATCHED AND (t.Price <> s.Price OR t.Name <> s.Name) THEN
    UPDATE SET t.Price = s.Price, t.Name = s.Name
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Sku, Name, Price) VALUES (s.Sku, s.Name, s.Price)
WHEN NOT MATCHED BY SOURCE AND t.IsActive = 1 THEN
    UPDATE SET t.IsActive = 0
OUTPUT $action AS Action, inserted.Sku, deleted.Price AS OldPrice, inserted.Price AS NewPrice;
Expected output
Action   Sku      OldPrice  NewPrice
-------  -------  --------  --------
UPDATE   KB-101   1499.00   1399.00
INSERT   MS-220   NULL      799.00
UPDATE   HD-009   2499.00   2499.00   -- deactivated (IsActive = 0)

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. Rows are matched on Sku.
  2. Matched rows are updated only if something changed.
  3. New SKUs are inserted.
  4. Products the supplier dropped are deactivated, not deleted.
  5. OUTPUT lists every change with old and new prices.

Real-world use case#

A nightly job loads the supplier’s price list into a staging table and one MERGE brings the catalogue up to date, writing the OUTPUT into an audit table.

Common mistakes#

Duplicate keys in the source

MERGE fails when one target row matches several source rows. Use ROW_NUMBER() or GROUP BY to deduplicate.

Forgetting the semicolon

MERGE must be terminated with ; or you get a syntax error.

Best practices#

  • Deduplicate the source
  • Only update when values differ
  • Use HOLDLOCK under concurrency
  • Log changes with OUTPUT

Remember this#

MATCHED → update, NOT MATCHED BY TARGET → insert, BY SOURCE → delete/deactivate.

End with ;

OUTPUT $action shows what happened.

Practice exercise#

Your task: Write the clause that inserts source rows that do not exist in the target (Sku, Name).

Show solution
SQL Illustrative
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Sku, Name) VALUES (s.Sku, s.Name)

Mini quiz#

MERGE Statement quizMultiple choice Question 1 of 1

Which clause handles target rows that are missing from the source?

Score so far: 0/0

Want more? Practise all SQL Server MCQs · SQL Server interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.