Sub topic 10
Upserting with MERGE
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements and that you know primary keys, foreign keys, and NOT NULL constraints. It also assumes you can run SQL in SQL*Plus, SQL Developer, or SQLcl. The examples use the demo tables dept_demo, emp_demo, emp_stage, and emp_archive. emp_stage has the same columns as emp_demo.
Why MERGE exists
A common batch task is "bring this table up to date with that data". Rows that already exist should be updated. Rows that do not exist should be inserted. Written as separate statements, you have to decide which rows fall into which group. You also scan the source twice.
MERGE does this in one statement. It reads a source, which can be a table, a view, or a subquery. It compares each source row with the target table using a join condition. Then it runs an UPDATE for matches and an INSERT for non-matches. This pattern is called an upsert (update or insert).
The first set of examples uses only the basic form. Conditional deletes and extra filters are covered in the next chapter.
The structure of a MERGE
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.salary = s.salary,
t.dept_id = s.dept_id,
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);Each part has one job:
| Clause | Purpose |
|---|---|
| `MERGE INTO emp_demo t` | Names the target table, the one that changes. The alias `t` is optional but keeps column references short. |
| `USING emp_stage s` | Names the source of rows. It can also be a subquery in parentheses. |
| `ON (...)` | The join condition. It decides whether a source row matches a target row. The parentheses are required. |
| `WHEN MATCHED THEN UPDATE` | Runs for each source row that has a matching target row. |
| `WHEN NOT MATCHED THEN INSERT` | Runs for each source row with no matching target row. |
Oracle evaluates the ON condition for every source row. A source row that matches is handled by the MATCHED branch. A source row that does not match is handled by the NOT MATCHED branch. Target rows that no source row matches are left alone.
A worked example
Start with the data from the earlier chapters, and add rows to the staging table. Employee 1 exists in emp_demo and gets a new salary. Employee 3 is new.
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');
COMMIT;Now run the MERGE from the previous section. Your client reports "2 rows merged". That count is the total of updated and inserted rows, and it does not tell you how many were of each kind.
Check the result:
SELECT emp_id, emp_name, salary
FROM emp_demo
ORDER BY emp_id;Ada's salary is now 9500, Grace is unchanged because she is not in the stage table, and Linus is a new row. The MERGE is still part of your open transaction until you commit, and ROLLBACK undoes all of it.
Rules that cause errors
You cannot update the columns in the ON clause
The columns used in the ON condition cannot appear on the left side of the UPDATE SET. This fails:
MERGE INTO emp_demo t
USING emp_stage s
ON (t.emp_id = s.emp_id)
WHEN MATCHED THEN
UPDATE SET t.emp_id = s.emp_id + 1000;Oracle raises ORA-38104: Columns referenced in the ON Clause cannot be updated. The reason is that the join decides which rows match, so changing the join column mid-statement would make the result ill-defined. If you need to change a key, use a separate UPDATE.
Each target row may be matched only once
If two source rows match the same target row, Oracle cannot decide which values to apply. It raises ORA-30926: unable to get a stable set of rows in the source tables. This usually means the source has duplicates for the key.
Suppose emp_stage contains two rows for employee 1. The MERGE fails. You can fix it by reducing the source to one row per key before merging. This version keeps the row with the highest salary:
MERGE INTO emp_demo t
USING (SELECT emp_id,
MAX(emp_name) AS emp_name,
MAX(dept_id) AS dept_id,
MAX(salary) AS salary,
MAX(status) AS status
FROM emp_stage
GROUP BY emp_id) 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);Note that taking MAX of each column separately can mix values from different source rows. Use it only when the columns agree, or pick the row with an analytic function such as ROW_NUMBER() when they do not.
Constraints still apply
MERGE is DML, so every constraint is checked. An inserted row with a dept_id that is not in dept_demo raises ORA-02291 (parent key not found). A new row with an emp_id that already exists cannot happen through the NOT MATCHED branch, because the join would have matched it. A duplicate can still arise from a concurrent session, which is covered below.
Using a subquery or literal values as the source
The source does not have to be a table. For a single row, use DUAL:
MERGE INTO emp_demo t
USING (SELECT 4 AS emp_id,
'Edsger' AS emp_name,
20 AS dept_id,
8800 AS salary
FROM dual) 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)
VALUES (s.emp_id, s.emp_name, s.dept_id, s.salary);This is the usual way to write a single-row upsert from application code. The status column is not listed in the INSERT, so it takes its default of 'ACTIVE'.
NULL values and the ON condition
The ON condition uses normal SQL comparison rules. If the key column is NULL on either side, t.emp_id = s.emp_id is not true, so the row does not match. A source row with a NULL key always goes to the NOT MATCHED branch. For a primary key column this then fails, because primary keys cannot be NULL. If your key can be NULL, you must write the condition to handle it, for example with NVL on both sides, and you should check that it is acceptable for those rows to match each other.
MERGE compared with the alternatives
Before MERGE, developers wrote an UPDATE and then checked SQL%ROWCOUNT in PL/SQL. If it was zero, they ran an INSERT. Another option was to INSERT and catch ORA-00001 (unique constraint violated), then UPDATE.
| Approach | Strengths | Weaknesses |
|---|---|---|
| UPDATE, then INSERT if no rows changed | Works for one row. Easy to read. | Needs PL/SQL. Slow for many rows because it runs one statement per row. |
| INSERT, catch ORA-00001, then UPDATE | Cheap when most rows are new. | Exceptions are costly when most rows already exist. |
| MERGE | One set-based statement. One scan of the source. | Needs a unique key in the source. Error messages are less specific. |
For sets of rows, MERGE is usually the best choice. It is also the clearest way to state the intent.
Concurrency
MERGE locks the rows it updates in the same way as UPDATE, so other sessions that try to change those rows wait until you commit or roll back. Rows that MERGE inserts are not visible to other sessions until you commit.
MERGE is not fully safe against two sessions upserting the same new key at the same moment. Both sessions can see "no match", and both try to INSERT. The second one waits for the first to commit, and then fails with ORA-00001. Your application should be ready to retry in that case. A primary key or unique constraint on the join column is what guarantees correctness here, so make sure the column has one.
Checking your results
Because the row count combines updates and inserts, verify results with queries when it matters. Compare counts before and after, or merge into a copy first. In PL/SQL, SQL%ROWCOUNT right after the MERGE gives the same combined number.
BEGIN
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
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);
DBMS_OUTPUT.PUT_LINE('Rows merged: ' || SQL%ROWCOUNT);
COMMIT;
END;
/Summary of key points
- MERGE reads a source once and routes each row to an UPDATE or an INSERT based on the
ONcondition. - The
ONcolumns cannot be updated (ORA-38104). - Each target row can be matched by at most one source row (ORA-30926).
- Constraints still apply, so missing parent rows raise ORA-02291.
- The row count is a combined total.
- Two sessions inserting the same new key can still collide with ORA-00001.
Exercise
Your MERGE fails with ORA-30926 (unable to get a stable set of rows). What is the most likely cause, and how do you fix it?
Show answer
Two or more source rows match the same target row, so Oracle cannot decide which values to apply. Fix it by making the source unique on the join key, for example by grouping with GROUP BY or by choosing one row per key with ROW_NUMBER() in the USING subquery.
Exercise
A MERGE reports "5 rows merged". Can you tell from that message how many rows were updated and how many were inserted? If not, how would you find out?
Show answer
No. The count is the sum of updated and inserted rows. To separate them, count the source rows that match the target before running the MERGE, for example with a query that joins the source to the target on the ON condition. Rows that match are the updates, and the rest are inserts.
Exercise
Why does this fail with ORA-38104, and what would you do instead? MERGE INTO empdemo t USING empstage s ON (t.empid = s.empid) WHEN MATCHED THEN UPDATE SET t.empid = s.empid + 1000;
Show answer
The column emp_id is used in the ON clause, and columns in the ON clause cannot be updated by the MERGE. Use a separate UPDATE statement to change the key value.