SQL Server MERGE

Summary: in this tutorial, you will learn how to use the SQL Server MERGE statement to update data in a table based on values matched from another table.

Introduction SQL Server MERGE Statement #

Suppose, you have two table called source and target tables, and you need to update the target table based on the values matched from the source table. There are three cases:

  1. The source table has some rows that do not exist in the target table. In this case, you need to insert rows that are in the source table into the target table.
  2. The target table has some rows that do not exist in the source table. In this case, you need to delete rows from the target table.
  3. The source table has some rows with the same keys as the rows in the target table. However, these rows have different values in the non-key columns. In this case, you need to update the rows in the target table with the values coming from the source table.

The following picture illustrates the source and target tables with the corresponding actions: insert, update, and delete: