The SQL statement MERGE (available from version 9i) provides the functionality of “INSERT or UPDATE” in a single statement.
The basic syntax is:
MERGE INTO <target> USING <source> ON (<join conditions>) WHEN MATCHED THEN UPDATE <SET clause> WHEN NOT MATCHED THEN INSERT (<column list>) VALUES (<expression list>);
where:
- <target> is the table that we’d like to insert new records into and/or update existing records in
- <source> is usually some SQL query (it may also be simply a table)
- <join conditions> specify the relationship between the source and the target – these conditions determine whether a row from the source exists in the target or not
Each row from the source is looked up in the target table, using the conditions specified in the ON clause. If the row exists in the target table, then the WHEN MATCHED clause is executed – the target row is updated. If the row does not exist in the target table, then the WHEN NOT MATCHED clause is executed – a new row is inserted into the target table.
Let’s take an example. Continue reading “The MERGE statement”
