The MERGE statement compares rows in a target table with rows from a source query or table.
Based on the comparison results, it can perform different actions using WHEN MATCHED and WHEN NOT MATCHED clauses.
The basic syntax structure is:
MERGE INTO target_table USING source_query ON (join_condition)
WHEN MATCHED THEN [UPDATE/DELETE operations]
WHEN NOT MATCHED THEN [INSERT operations]
The purpose of using MERGE statements is to be able to use a query to add, modify, and delete rows from a table based on conditions defined in the query.
This eliminates the need for separate INSERT, UPDATE, and DELETE statements and ensures atomic execution of all operations.
Example:
MERGE INTO table_merge a
USING
(
SELECT id1, 1 AS flag FROM table_merge WHERE id1 IN (12,13)
UNION ALL
SELECT 18 as id1, 1 AS flag FROM DUAL
UNION ALL
SELECT id1, 0 AS flag FROM table_merge WHERE id1 IN (14,15)
) b
ON (b.id1 = a.id1)
WHEN MATCHED THEN
UPDATE SET a.code = a.code || '-MATCHED'
DELETE WHERE b.flag != 1
WHEN NOT MATCHED THEN
INSERT (a.id1, a.code)
VALUES (b.id1, 'NOT MATCHED');
In this example:
- Rows with id1 IN (12,13) will be updated with '-MATCHED' suffix.
- Rows with id1 IN (14,15) will be deleted (flag = 0).
- A new row with id1 = 18 will be inserted.
- Rows with id1 IN (11,16,17) remain unchanged.
Select data from the "
table_merge
" table:
SELECT id1, code FROM table_merge;
Query result:
id1 code
----- ----
11 A_11
12 A_12-MATCHED
13 A_13-MATCHED
16 A_16
17 A_17
18 NOT MATCHED
The following rows were deleted:
id1 code
----- ----
14 A_14
15 A_15