What does the MERGE command do?
The MERGE command in SQL is used to combine data from two tables - it lets you insert new records, update existing ones, and remove duplicates if needed, all at once. It's often called "UPSERT" (update + insert).
Syntax (general form):
sql
MERGE INTO Target_Table AS T
USING Source AS S
ON T.Key = S.Key
WHEN MATCHED THEN
UPDATE SET T.Field1 = S.Field1, T.Field2 = S.Field2
WHEN NOT MATCHED THEN
INSERT (Field1, Field2) VALUES (S.Field1, S.Field2);Example:
sql
MERGE INTO Employees AS E
USING NewEmployees AS N
ON E.ID = N.ID
WHEN MATCHED THEN
UPDATE SET E.Name = N.Name, E.DepartmentID = N.DepartmentID
WHEN NOT MATCHED THEN
INSERT (ID, Name, DepartmentID) VALUES (N.ID, N.Name, N.DepartmentID);What it does
- If a record with that
IDalready exists in theEmployeestable → it updates the data (UPDATE). - If the record doesn't exist → it adds a new one (
INSERT).
Why it's used:
- It's convenient for syncing tables, importing new data while updating old data at the same time.
- It avoids the need for separate code to check whether a record exists before inserting or updating it.
Put simply,
MERGEis a command for "update or insert" a record into a table, depending on whether it already exists.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.