Sql merge statement with example

by Yogi P - December 8, 2022

SQL MERGE statement

In SQL, the MERGE statement is used to combine data from two or more tables into a single table. It allows you to update, insert, or delete data in a target table based on data from a source table. This is useful when you want to keep your target table up-to-date with the latest data from the source table, without having to write separate UPDATE, INSERT, and DELETE statements.

The syntax for the MERGE statement is:

MERGE INTO target_table AS T
USING source_table AS S
ON condition
WHEN MATCHED THEN
UPDATESET col1 = value1, col2 = value2, ...
WHEN NOT MATCHED THEN
INSERT (col1, col2, ...) VALUES (value1, value2, ...)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;

Here, target_table is the table that you want to update, insert, or delete data in, and source_table is the table that you are using as the source of data. The ON clause specifies the condition that must be met in order for the MERGE statement to take action (i.e. update, insert, or delete data).

The WHEN MATCHED clause specifies the action to take if a matching record is found in the target table (i.e. update the record with new data from the source table).

The WHEN NOT MATCHED clause specifies the action to take if a matching record is not found in the target table (i.e. insert a new record from the source table). And the WHEN NOT MATCHED BY SOURCE clause specifies the action to take if a record exists in the target table but not in the source table (i.e. delete the record from the target table).

Here is an example of using MERGE to combine data from two tables:

Suppose we have two tables, students and courses, with the following data:
students:
+—-+——-+——–+
| id | name | course |
+—-+——-+——–+
| 1 | Alice | Math |
| 2 | Bob | English |
| 3 | Carol | CS |
+—-+——-+——–+
courses:
+—-+—————-+
| id | course_name |
+—-+—————-+
| 1 | Math |
| 2 | English |
| 3 | Computer Science |
+—-+—————-+

If we want to combine the data from these two tables into a single table, we can use the MERGE statement:

MERGE INTO students AS S
USING courses AS C
ON S.course = C.course_name
WHEN MATCHED THEN
UPDATESET S.course_id = C.id
WHEN NOT MATCHED THEN
INSERT (name, course, course_id) VALUES (S.name, S.course, C.id)

This would produce the following result:

+—-+——-+——–+———–+
| id | name | course | course_id |
+—-+——-+——–+———–+
| 1 | Alice | Math | 1 |
| 2 | Bob | English

Share on: Share YogiRaj B.Ed Study Notes on twitter Share YogiRaj B.Ed Study Notes on facebook Share YogiRaj B.Ed Study Notes on WhatsApp
Latest Posts

CDMA Full Form

April 19, 2024

Table of 14

April 11, 2024

Tables 11 to 20

March 11, 2024

Tense Chart

December 22, 2023

Table of 13

December 20, 2023
Search this Blog
Categories