Search code examples
sqlsql-serversql-merge

SQL merge not matched by target vs not matched by source


What is the difference between NOT MATCHED BY SOURCE vs NOT MATCHED BY TARGET?

For example:

Does WHEN NOT MATCHED BY SOURCE mean that the records exist in the target but not in the source? - so we can delete them ?

and WHEN NOT MATCHED BY TARGET - mean the records exists in the source but not in the target? so we can insert them?


Solution

  • WHEN NOT MATCHED BY TARGET - You should use this clause to insert new rows into the target table. The rows you insert into the table are those rows in the source table for which there are no matching rows in the target.

    WHEN NOT MATCHED BY SOURCE - If you want to delete a row from the target table that does not match a row in the source table