Description
The MERGE INTO statement is used to update records in the target table based on values from the source table or subquery. This feature can be used to synchronize data in the target table when the source table contains new rows (to be inserted), modified rows (to be updated), and deleted rows (to be deleted).
Syntax
Parameter Description
target_table: Specifies the target table, aliases can be used.source_table: Specifies the table or subquery to be compared with the target table, aliases can be used.merge_condition: Defines how rows from the source table match with rows from the target table, returns a boolean expression.WHEN MATCHED [ AND matched_condition ]: Executes theWHEN MATCHEDclause when a source row matches a target table row based onmerge_conditionand optionalmatched_condition.- If no
WHEN MATCHEDcondition evaluates to true for a pair of source and target rows that match themerge_condition, the target row remains unchanged. - If there are multiple
WHEN MATCHEDclauses, they are evaluated in the order specified. EachWHEN MATCHEDclause must have amatched_condition.
- If no
WHEN NOT MATCHED [ AND not_matched_condition ]: Executes theWHEN NOT MATCHEDclause when a source row does not match any row in the target table based onmerge_conditionand optionalnot_matched_condition.- If there are multiple
WHEN NOT MATCHEDclauses, they are evaluated in the order specified.
- If there are multiple
matched_action:DELETE: Deletes the matching target table row.UPDATE: Updates the matching target table row. UseUPDATE SET column1 = source.column1 [, column2 = source.column2 ...].
not_matched_action:INSERT: Inserts into the target table using the corresponding columns from the source dataset, supports specifying fields for insertion. For unspecified target columns,NULLis inserted.
Notes
When executing the MERGE INTO statement, the system will report an error if it may produce uncertain results. The reasons for this situation include:
- If the
ONclause causes more than one row from the source table to match a row in the target table, the SQL standard requires an error to be raised. - If the
ONclause causes more than one row from the source table to match a row in the target table, and there are still multiple records after filtering with theAND case_predicatecondition. - When both WHEN MATCHED and WHEN NOT MATCHED statements are present, the first statement in the MERGE INTO statement must be WHEN MATCHED, otherwise a syntax error will occur. The following is an incorrect example:
