Back to results for “Error Handling”
SQL Server › Merge Statement (Upsert)

How do you safely test a MERGE statement before running it against real production data?

Intermediate

Answer

You can wrap the MERGE statement in a transaction, run it, review the affected row counts and results using the OUTPUT clause, and then roll back the transaction to undo the changes, giving you a safe way to verify the exact behavior of a complex MERGE statement before committing to running it against your actual production data.
BEGIN TRANSACTION;
MERGE INTO Products AS target
USING StagingProducts AS source
ON target.ProductId = source.ProductId
WHEN MATCHED THEN UPDATE SET target.Price = source.Price
OUTPUT $action, inserted.ProductId;
-- Review the output, then decide
ROLLBACK TRANSACTION;
Real-world example A developer tests a new MERGE statement against a copy of production data inside a transaction, reviewing the OUTPUT results carefully before rolling back, then finally running the confirmed correct statement for real once satisfied.

Common follow-ups: Is it safe to test destructive statements like MERGE directly against production data this way?;What should you check in the OUTPUT results before trusting the MERGE logic is correct?