Sub topic 10
Upserting with MERGE
Prerequisites: you should know basic SELECT, INSERT, and UPDATE statements. You should also understand primary keys and transactions. This chapter assumes that emp_demo and emp_stage already exist with the same columns.
A MERGE statement combines an update and an insert. It compares rows in a target table with rows from a source query. When a source row matches a target row, Oracle updates the target. When no target row matches, Oracle inserts the source row.
This pattern is called an upsert, which means “update or insert.”
The MERGE working model
The ON clause defines how Oracle finds a match. In this example, emp_id identifies an employee in both tables.
MERGE INTO emp_demo t
USING emp_stage s
ON (t.emp_id = s.emp_id)
WHEN MATCHED THEN
UPDATE SET t.emp_name = s.emp_name,
t.dept_id = s.dept_id,
t.salary = s.salary,
t.status = s.status
WHEN NOT MATCHED THEN
INSERT (emp_id, emp_name, dept_id, salary, status)
VALUES (s.emp_id, s.emp_name, s.dept_id, s.salary, s.status);The aliases t and s represent the target and source. The target is emp_demo. The source is emp_stage.
Oracle processes each source row as follows:
- It evaluates the
ONcondition. - If a target employee has the same
emp_id, Oracle runs theUPDATEclause. - If no target employee matches, Oracle runs the
INSERTclause. - Oracle checks constraints and records the changes in the current transaction.
The source can be a table, view, or query. For example, a query can filter or transform staging data before the merge.
MERGE INTO emp_demo t
USING (
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_stage
WHERE status <> 'IGNORED'
) s
ON (t.emp_id = s.emp_id)
WHEN MATCHED THEN
UPDATE SET t.salary = s.salary,
t.status = s.status
WHEN NOT MATCHED THEN
INSERT (emp_id, emp_name, dept_id, salary, status)
VALUES (s.emp_id, s.emp_name, s.dept_id, s.salary, s.status);
COMMIT;Source uniqueness and common errors
The source should contain at most one row for each target key. If two source rows match the same target row, Oracle cannot update that target row twice in one statement. It raises ORA-30926: unable to get a stable set of rows in the source tables.
Check for duplicate keys before merging:
SELECT emp_id, COUNT(*) AS occurrences
FROM emp_stage
GROUP BY emp_id
HAVING COUNT(*) > 1;You can remove duplicates in the source query with a business rule, such as selecting the newest record with ROW_NUMBER(). Do not remove duplicates arbitrarily if each row represents important data.
A MERGE does not commit automatically. Use COMMIT after checking the results, or use ROLLBACK if the changes are not correct.
Exercise
What happens when a source row in emp_stage has an emp_id that does not exist in emp_demo?
Show answer
The row follows the WHEN NOT MATCHED branch and is inserted into emp_demo.