Sub topic 3
Upserting with MERGE
This chapter assumes you know INSERT, UPDATE, and DELETE, that you can read a primary key, and that you can run SQL in SQL Developer or SQLcl. The examples use the tables created in the earlier chapters: deptdemo, empdemo, empstage, and emparchive.
MERGE is one statement that updates matching rows and inserts missing rows. This combined action is called an upsert. MERGE reads a source, usually a staging table, and compares each source row with the target table using a join condition.
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
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);MERGE with conditional UPDATE, DELETE, and INSERT
Add a DELETE WHERE clause to the MATCHED branch to remove rows after they are updated. Oracle evaluates the condition against the updated values, so only matched rows that satisfy it are deleted.
Row locks and concurrent sessions
An UPDATE or MERGE locks each row it changes. A second session that changes the same row waits until the first session runs COMMIT or ROLLBACK. Readers do not wait for these locks. Keep transactions short so that other sessions are not blocked for long.
Keeping batch loads going with LOG ERRORS
By default, one bad row stops an INSERT. Create an error log table once, then add a LOG ERRORS clause so that bad rows are written to it and the load continues.
EXEC DBMS_ERRLOG.CREATE_ERROR_LOG('EMP_DEMO');
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_stage
LOG ERRORS INTO err$_emp_demo ('load_1') REJECT LIMIT UNLIMITED;Loading several tables with INSERT ALL and INSERT FIRST
INSERT ALL writes each source row to every table whose WHEN condition matches. INSERT FIRST writes each row to the first table whose condition matches.
CREATE TABLE emp_high AS SELECT emp_id, salary FROM emp_demo WHERE 1 = 0;
CREATE TABLE emp_regular AS SELECT emp_id, salary FROM emp_demo WHERE 1 = 0;
INSERT FIRST
WHEN salary >= 10000 THEN INTO emp_high (emp_id, salary) VALUES (emp_id, salary)
ELSE INTO emp_regular (emp_id, salary) VALUES (emp_id, salary)
SELECT emp_id, salary FROM emp_demo;Direct-path inserts with the APPEND hint
The APPEND hint asks Oracle to write rows above the table's high-water mark instead of reusing free space. This is faster for large loads.
INSERT /*+ APPEND */ INTO emp_archive
SELECT * FROM emp_demo WHERE status = 'INACTIVE';
COMMIT;
SELECT COUNT(*) FROM emp_archive;Exercise
In the empstage MERGE, which clause runs when a staged empid has no match in emp_demo?
Show answer
The WHEN NOT MATCHED THEN INSERT clause runs, and it adds the staged row to emp_demo.