SQL Interview: 35 T-SQL Merge Statement Clauses

SQL Interview: 35 T-SQL Merge Statement Clauses

This is a post in the SQL Interview series. These aren’t trick or gotcha questions, they’re just questions designed to scope out a candidate’s knowledge around SQL Server and Azure SQL Database.

Section: Development Level: Medium

Question:

You are reading a T-SQL script. One MERGE statement merges data from TableA into TableB, and contains two clauses:

WHEN NOT MATCHED BY SOURCE

and

WHEN NOT MATCHED BY TARGET

What is the difference between these? And what is the most common operation that’s executed in each of these clauses?

Answer:

The first clause says to take an action when TableA does not contain a row but TableB does contain a row that matches it, based on the condition in the ON clause. A common operation in this case is a DELETE.

The second clause says to take an action when TableB does not contain a row but TableA does contain a row that matches it, based on the condition in the ON clause. A common operation in this case is an INSERT.

2025-04-11