Sub topic 14
Loading Several Tables with `INSERT ALL` and `INSERT FIRST`
This chapter assumes that you can write SELECT statements with WHERE clauses and understand primary keys, foreign keys, and transactions. It also assumes that emp_demo contains employee rows with emp_id, salary, and status columns.
A multitable insert reads a source query once and sends each source row to one or more target tables. This is useful when one incoming row must create several related records or when rows must be routed to different tables.
`INSERT ALL`: send a row to every matching branch
INSERT ALL evaluates every branch for every source row. A source row can therefore be inserted into several target tables.
The following example creates two empty tables and records every employee in both tables:
CREATE TABLE emp_audit (
emp_id NUMBER,
audit_note VARCHAR2(100)
);
CREATE TABLE emp_snapshot (
emp_id NUMBER,
salary NUMBER(8,2)
);
INSERT ALL
INTO emp_audit (emp_id, audit_note)
VALUES (emp_id, 'Loaded into snapshot')
INTO emp_snapshot (emp_id, salary)
VALUES (emp_id, salary)
SELECT emp_id, salary
FROM emp_demo;The SELECT query is the source. Its column names are available to each INTO clause. For every employee, Oracle inserts one row into emp_audit and one row into emp_snapshot.
You can also add conditions. In this form, Oracle checks every WHEN condition independently:
INSERT ALL
WHEN salary >= 10000 THEN
INTO emp_high (emp_id, salary)
VALUES (emp_id, salary)
WHEN status = 'ACTIVE' THEN
INTO emp_regular (emp_id, salary)
VALUES (emp_id, salary)
SELECT emp_id, salary, status
FROM emp_demo;An employee with a salary of 12,000 and status ACTIVE goes into both tables.
`INSERT FIRST`: stop after the first match
INSERT FIRST also checks branches in order, but it inserts a source row only into the first branch whose condition is true. Later branches are skipped.
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;This routes high-paid employees to emp_high and every other employee to emp_regular. The ELSE branch is optional. Without it, a source row that matches no condition is ignored.
How the routing works
Each target table must have compatible columns and constraints. A failure in an ordinary multitable insert can roll back the statement, so test the source query and target constraints before loading production data.
Exercise
An employee has salary 12000 and status ACTIVE. With INSERT ALL branches for salary >= 10000 and status = 'ACTIVE', how many target rows can this employee create? With INSERT FIRST, how many can it create?
Show answer
INSERT ALL can create two target rows, one for each true condition. INSERT FIRST creates only one row, in the first matching branch.