MERGE¶
Inserts, updates, and deletes values in a table that are based on values in a second table or a subquery. Merging can be useful if the second table is a change log that contains new rows (to be inserted), modified rows (to be updated), or marked rows (to be deleted) in the target table.
The command supports semantics for handling the following cases:
Values that match (for updates and deletes).
Values that don’t match (for inserts).
Syntax¶
Where:
Parameters¶
target_tableSpecifies the table to merge.
sourceSpecifies the table or subquery to join with the target table.
join_exprSpecifies the expression on which to join the target table and source.
matchedClause (for updates or deletes)¶
WHEN MATCHED ... AND case_predicateOptionally specifies an expression which, when true, causes the matching case to be executed.
Default: No value (matching case is always executed)
WHEN MATCHED ... THEN { UPDATE { ALL BY NAME | SET ... } | DELETE }Specifies the action to perform when the values match.
ALL BY NAMEUpdates all columns in the target table with values from the source. Each column in the target table is updated with the values of the column with the same name from the source.
The target table and source must have the same number of columns and the same names for all of the columns. However, the column order can be different between the target table and the source.
SET col_name = expr [ , col_name = expr ... ]Updates the specified column in the target table by using the corresponding expression for the new column value (can refer to both the target and source relations).
In a single
SETsubclause, you can specify multiple columns to update.DELETEDeletes the rows in the target table when they match the source.
notMatchedClause (for inserts)¶
WHEN NOT MATCHED ... AND case_predicateOptionally specifies an expression which, when true, causes the not-matching case to be executed.
Default: No value (not-matching case is always executed)
WHEN NOT MATCHED ... THEN INSERT.{ ALL BY NAME | [ ( col_name [ , ... ] ) ] VALUES ( expr [ , ... ] ) }Specifies the action to perform when the values don’t match.
ALL BY NAMEInserts all columns in the target table with values from the source. Each column in the target table is inserted with the values of the column with the same name from the source.
The target table and source must have the same number of columns and the same names for all of the columns. However, the column order can be different between the target table and the source.
( col_name [ , ... ] )Optionally specifies one or more columns in the target table to be inserted with values from the source.
Default: No value (all columns in the target table are inserted)
VALUES ( expr [ , ... ] )Specifies the corresponding expressions for the inserted column values (must refer to the source relations).
Usage notes¶
A single MERGE statement can include multiple matching and not-matching clauses (that is,
WHEN MATCHED ...andWHEN NOT MATCHED ...).Any matching or not-matching clause that omits the
ANDsubclause (default behavior) must be the last of its clause type in the statement (for example, aWHEN MATCHED ...clause can’t be followed by aWHEN MATCHED AND ...clause). Doing so results in an unreachable case, which returns an error.
Duplicate join behavior¶
When multiple rows in the source table match a single row in the target table, the results can be deterministic or nondeterministic. This section describes MERGE behavior for these use cases.
Nondeterministic results for UPDATE and DELETE¶
When a merge joins a row in the target table against multiple rows in the source, the following join conditions produce nondeterministic results (that is, the system is unable to determine the source value to use to update or delete the target row):
A target row is selected to be updated with multiple values (for example,
WHEN MATCHED ... THEN UPDATE).A target row is selected to be both updated and deleted (for example,
WHEN MATCHED ... THEN UPDATE,WHEN MATCHED ... THEN DELETE).
In this situation, the outcome of the merge depends on the value specified for the ERROR_ON_NONDETERMINISTIC_MERGE session parameter:
If TRUE (default value), the merge returns an error.
If FALSE, one row from among the duplicates is selected to perform the update or delete; the row selected is not defined.
Deterministic results for UPDATE and DELETE¶
Deterministic merges always complete without error. A merge is deterministic if it meets at least one of the following conditions for each target row:
One or more source rows satisfy the
WHEN MATCHED ... THEN DELETEclauses, and no other source rows satisfy anyWHEN MATCHEDclausesExactly one source row satisfies a
WHEN MATCHED ... THEN UPDATEclause, and no other source rows satisfy anyWHEN MATCHEDclauses.
This makes MERGE semantically equivalent to the UPDATE and DELETE commands.
Note
To avoid errors when multiple rows in the data source (that is, the source table or subquery) match the target table based on the ON condition, use GROUP BY in the source clause to ensure that each target row joins against one row (at most) in the source.
In the following example, assume src includes multiple rows with the same k value. It’s ambiguous which values (v) will
be used to update rows in the target row with the same value of k. By using the MAX function and GROUP BY, the query clarifies exactly
which value of v from src is used:
Deterministic results for INSERT¶
Deterministic merges always complete without error.
If the MERGE statement contains a WHEN NOT MATCHED ... THEN INSERT clause, and if there are no matching rows in the target, and if the
source contains duplicate values, then the target gets one copy of the row for each copy in the source. For an example,
see Perform a merge with source duplicates.
Examples¶
The following examples use the MERGE command:
Perform a basic merge that updates values¶
The following example performs a basic merge that updates values in the target table by using values from the source table. Create and load two tables:
Display the values in the tables:
Run the MERGE statement:
Display the new values in the target table (the source table is unchanged):
Perform a basic merge with multiple operations¶
Perform a basic merge with a mix of operations (INSERT, UPDATE, and DELETE).
Create and load two tables:
Display the values in the tables:
The following merge example performs the following actions on the merge_example_mult_target table:
Deletes the row with
idset to1because themarkedcolumn for the row with the sameidisYinmerge_example_mult_source.Updates the
valandstatusvalues in the row withidset to2with values in the row with the sameidinmerge_example_mult_source, becauseisnewstatusis set to1for the same row inmerge_example_mult_source.Updates the
valvalue in the row withidset to3with the value in the row with the sameidinmerge_example_mult_source. The MERGE statement doesn’t update thestatusvalue inmerge_example_mult_targetbecauseisnewstatusis set to0for this row inmerge_example_mult_source.Inserts the row with
idset to4because the row exists inmerge_example_mult_sourceand there is no matching row inmerge_example_mult_target.
To see the results of the merge, display the values in the merge_example_mult_target table:
Perform a merge by using ALL BY NAME¶
The following example performs a merge that inserts and updates values in the target table by using values from the
source table. The example uses the WHEN MATCHED ... THEN ALL BY NAME and
WHEN NOT MATCHED ... THEN ALL BY NAME subclauses to specify that the merge applies to all columns.
Create two tables with the same number of columns and the same names for the columns, but with a different order for two of the columns:
Load the tables:
Display the values in the tables:
Run the MERGE statement:
Display the new values in the target table:
Perform a merge with source duplicates¶
Perform a merge in which the source has duplicate values and the target has no matching values. All copies of the source record are inserted into the target. For more information, see Deterministic results for INSERT.
Truncate both tables and load new rows into the source table that include duplicates:
The merge_example_target has no values. Display the values in the
merge_example_source table:
Run the MERGE statement:
Display the new values in the target table:
Perform a merge with deterministic and nondeterministic results¶
Merge records by using joins that produce nondeterministic and deterministic results.
Create and load two tables:
When you perform the merge in the following example, multiple updates conflict with each other. If
the ERROR_ON_NONDETERMINISTIC_MERGE session parameter is set to true, the MERGE statement
returns an error. Otherwise, the MERGE statement updates merge_example_target_clone.v with a value
(for example, 11, 12, or 13) from one of the duplicate rows (row not defined):
Updates and deletes conflict with each other. If the ERROR_ON_NONDETERMINISTIC_MERGE session
parameter is set to true, the MERGE statement returns an error. Otherwise, the MERGE statement either deletes the row
or updates merge_example_target_clone.v with a value (for example, 12 or 13) from one of the
duplicate rows (row not defined):
Multiple deletes don’t conflict with each other. Joined values that don’t match any clause don’t prevent
the delete (merge_example_src.v = 13). The MERGE statement succeeds and the target row is deleted:
Joined values that don’t match any clause don’t prevent an update (merge_example_src.v = 12, 13).
The MERGE statement succeeds and the target row is set to target.v = 11:
Use GROUP BY in the source clause to ensure that each target row joins against one row in the source:
Perform a merge based on DATE values¶
In the following example, the members table stores the names, addresses, and current fees (members.fee) paid to a
local gym. The signup table stores each member’s signup date (signup.date). The MERGE statement applies a standard
$40 fee to members who joined the gym more than 30 days ago, after the free trial expired: