Sub topic 11
MERGE with conditional UPDATE, DELETE, and INSERT
This chapter assumes you know the basic MERGE ... USING ... ON ... WHEN MATCHED / NOT MATCHED form from the previous chapter. It also assumes you have the dept_demo, emp_demo, and emp_stage tables from the setup chapter. A plain MERGE touches every matched row and inserts every unmatched row. Real loads need more control: skip rows that did not change, remove rows that the source marks as gone, and refuse to insert rows you do not want. Oracle provides three optional pieces for this: a WHERE on the update branch, a DELETE WHERE on the update branch, and a WHERE on the insert branch.
The full syntax
MERGE INTO target t
USING source s
ON (join_condition)
WHEN MATCHED THEN
UPDATE SET t.col = s.col, ...
[WHERE update_condition]
[DELETE WHERE delete_condition]
WHEN NOT MATCHED THEN
INSERT (columns) VALUES (values)
[WHERE insert_condition];Each piece answers a different question:
| Clause | Question it answers | Which columns it can see |
|---|---|---|
| `UPDATE ... WHERE` | Is this matched row worth updating? | Target values before the update, and source values |
| `DELETE WHERE` | Should this updated row now be removed? | Target values after the update, and source values |
| `INSERT ... WHERE` | Should this unmatched source row be inserted? | Source columns only |
The DELETE clause has no statement of its own. It is part of the WHEN MATCHED branch, so it can only remove rows that the update branch actually updated. That rule causes most of the surprises in this chapter.
Decision flow for each source row
A worked example
Start with a known state. If earlier chapters left different data in the tables, adjust the values to match.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
VALUES (6, 'Barbara', 10, 7500, 'ACTIVE');
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary, status)
VALUES (1, 'Ada', 20, 9500, 'ACTIVE');
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary, status)
VALUES (3, 'Linus', 20, 8000, 'ACTIVE');
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary, status)
VALUES (4, 'Edsger', 10, 6500, 'TERMINATED');
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary, status)
VALUES (6, 'Barbara', 10, 7500, 'TERMINATED');
COMMIT;Now run the conditional MERGE:
MERGE INTO emp_demo t
USING emp_stage s
ON (t.emp_id = s.emp_id)
WHEN MATCHED THEN
UPDATE SET t.salary = s.salary,
t.dept_id = s.dept_id,
t.status = s.status
WHERE (t.salary <> s.salary
OR t.dept_id <> s.dept_id
OR t.status <> s.status)
DELETE WHERE (t.status = 'TERMINATED')
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)
WHERE (s.status <> 'TERMINATED');Here is what happens to each source row:
- Employee 1 (Ada) matches. The salary differs (9000 against 9500), so the update runs. Her status is still
ACTIVE, soDELETE WHEREis false and she stays. - Employee 3 (Linus) has no match. His status is not
TERMINATED, so he is inserted. - Employee 4 (Edsger) has no match, but the insert
WHEREis false. He is skipped, so a person who was never in the target is not added just to be marked terminated. - Employee 6 (Barbara) matches. Her status changes to
TERMINATED, so the update runs.DELETE WHEREthen sees the new status and deletes her row.
SQL*Plus reports 3 rows merged. The count includes the deleted row. Query emp_demo afterward to confirm that Ada has salary 9500, Linus exists, and Barbara and Edsger do not.
How DELETE WHERE sees the data
DELETE WHERE is evaluated after the update has been applied to the row. That is why the example tests t.status = 'TERMINATED'. By that point t.status already holds the value copied from the source. If you wrote t.status = 'ACTIVE' expecting the old value, you would delete the wrong rows.
The second rule is that only updated rows are candidates. Suppose a target row is already TERMINATED and the stage row repeats the same values. The update WHERE is false, the row is not updated, and DELETE WHERE is never tested for it. The row stays. If you want to delete it, drop the update WHERE, or add a separate DELETE statement.
Choosing the update filter
The update WHERE avoids needless work. Rewriting a row with the same values still generates undo and redo, fires row triggers, and takes a row lock. On a large load where most rows are unchanged, the filter can matter a lot.
The <> comparisons in the example have a flaw. If either side is NULL, the result is unknown, not true, so a change from NULL to a value is skipped. The salary column allows nulls. Use LNNVL, which returns true when its condition is false or unknown, to catch those cases:
WHERE (LNNVL(t.salary = s.salary) OR LNNVL(t.dept_id = s.dept_id) OR LNNVL(t.status = s.status))You can also use DECODE(t.salary, s.salary, 0, 1) = 1, which treats two nulls as equal.
Restrictions and common errors
| Error | Cause | Fix |
|---|---|---|
| ORA-38104: Columns referenced in the ON Clause cannot be updated | The `SET` list assigns a column that appears in the `ON` condition | Remove that column from `SET`, or change the join columns |
| ORA-30926: unable to get a stable set of rows in the source tables | Two or more source rows match the same target row | Make the source unique per join key |
| ORA-00001: unique constraint violated | The insert branch creates a key that already exists on a different unique index | Fix the data, or use `LOG ERRORS` (covered in a later chapter) |
| ORA-02291: integrity constraint violated, parent key not found | Inserted or updated `dept_id` has no row in `dept_demo` | Load parent rows first |
ORA-30926 is the one you will meet most often. Oracle refuses to apply two different source rows to one target row, because the final value would depend on row order. Deduplicate the source in the USING clause:
MERGE INTO emp_demo t
USING (SELECT emp_id, emp_name, dept_id, salary, status
FROM (SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY s.emp_id
ORDER BY s.salary DESC) AS rn
FROM emp_stage s)
WHERE rn = 1) s
ON (t.emp_id = s.emp_id)
WHEN MATCHED THEN
UPDATE SET t.salary = s.salary
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);Order by something meaningful, such as a load timestamp, so that the winning row is predictable. emp_stage has no such column, so salary stands in here.
The ON condition must also be deterministic. If it uses a column that is not unique in the target, one source row can match several target rows. That is allowed, and every one of them is updated.
Optional branches
You can write a MERGE with only one branch. A statement with only WHEN NOT MATCHED inserts missing rows and ignores existing ones. A statement with only WHEN MATCHED updates without ever inserting. Use these when you want an "insert if missing" or "update only if present" step without writing a separate existence check.
When to prefer separate statements
MERGE is not always the right tool. Keep these limits in mind:
- You cannot use
RETURNING INTOwith MERGE, so you cannot capture changed values in the same statement. - Complex conditions inside one MERGE are harder to read and test than two short statements.
- A very large update branch holds row locks until you commit, so other sessions that change the same rows will wait on you.
Use MERGE when update, insert, and optional delete all depend on one join to the same source. Use separate statements when the branches have different sources or different filters that do not share a join.
Exercise
A target row has status 'TERMINATED', and the matching source row is identical in every column. The MERGE has an UPDATE ... WHERE that compares all columns with <> and a DELETE WHERE (t.status = 'TERMINATED'). Is the row deleted? Why or why not?
Show answer
No. The update WHERE is false because nothing differs, so the row is not updated. DELETE WHERE only applies to rows that the update branch changed, so the row is never tested and stays in the table.
Exercise
Your MERGE fails with ORA-30926. List two ways to find the cause, then name one way to fix it.
Show answer
Run SELECT empid, COUNT(*) FROM empstage GROUP BY empid HAVING COUNT(*) > 1 to find duplicate source keys, or check whether the ON condition matches one target row to several source rows. Fix it by deduplicating the source inside the USING subquery, for example with ROWNUMBER() OVER (PARTITION BY emp_id ORDER BY ...) and keeping rn = 1.
Exercise
Write the INSERT branch of a MERGE that adds only source rows with a salary of at least 5000, and say which columns its WHERE clause may reference.
Show answer
WHEN NOT MATCHED THEN INSERT (empid, empname, deptid, salary, status) VALUES (s.empid, s.empname, s.deptid, s.salary, s.status) WHERE (s.salary >= 5000). The insert WHERE may reference only source columns, because no target row exists yet.