MERGE
MERGE is a command in SQL that allows users to blend and synchronize two tables based on a related column between them. It is a cohesive way of inserting, deleting, or updating data in a target table, correlating with data in a source table. It essentially merges data between tables, reducing the need for multiple Insert, Update, and Delete commands.
Example
Output
Explanation
The MERGE statement is a combination of the INSERT, DELETE and UPDATE commands to simultaneously perform these operations in our Student table. In this example, first, two tables namely Student and NewStudentData are created. Then, the values from NewStudentData are merged into the Student table. If the StudentID exists in both tables, the Age is updated in the Student table. If the StudentID is found only in the NewStudentData table, a new row is inserted in the Student table. The output tells us the number of rows affected in each operation.
Example
Output
Explanation
In the given example, the MERGE
statement is used to synchronize the target_table
with the source_table
. The ON
clause defines the condition for the match, in this case, when the column1
in both tables is equal.
When a match is found, the MATCHED
clause is executed updating column2
in the target_table
with the value from source_table
.
If no match is found, the NOT MATCHED
clause is executed, where a new row is inserted into the target_table
with the column1
and column2
values from source_table
.
The output ‘2 rows merged.’ indicates that the operation affected two rows in the target_table
.