Senior Detailed answer DML SQL & Databases

Write a MERGE statement example for upsert.

Short answer: MERGE matches source to target ON a key, then WHEN MATCHED UPDATE, WHEN NOT MATCHED INSERT. Discuss concurrency and that some teams prefer separate UPDATE/INSERT.

Sample solution

T-SQL
MERGE INTO Employees AS t
USING (SELECT @EmpId AS EmpId, @Name AS Name, @Salary AS Salary) AS s
ON t.EmpId = s.EmpId
WHEN MATCHED THEN
    UPDATE SET Name = s.Name, Salary = s.Salary
WHEN NOT MATCHED THEN
    INSERT (EmpId, Name, Salary) VALUES (s.EmpId, s.Name, s.Salary);
Know that MERGE has historically had race/edge-case caveats — saying so shows maturity.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details