Sub topic 5
One Trigger, Several Events: INSERTING, UPDATING, DELETING
This chapter assumes you can write a basic row-level trigger, read :OLD and :NEW, and use IF statements in PL/SQL. You should also know that a trigger's DML runs inside the transaction of the statement that fired it.
By the end you will be able to cover several DML events with one trigger. You will be able to tell the events apart inside the body, and you will know the edge cases where the predicates behave in surprising ways.
Why combine events
Some logic belongs to more than one event. An audit trail records inserts, updates, and deletes. A "no changes on weekends" rule applies to all three. Writing three triggers means three copies of the shared code, and the copies drift apart over time.
Oracle lets you list events in the triggering clause, joined with OR:
BEFORE INSERT OR UPDATE OR DELETE ON employeesThe trigger fires once for each event that matches. Inside the body, you need a way to ask which event fired it. That is the job of the conditional predicates.
The three predicates
INSERTING, UPDATING, and DELETING are Boolean values that exist only inside a trigger body. Exactly one of them is TRUE for any given firing.
| Predicate | TRUE when | `:OLD` values | `:NEW` values |
|---|---|---|---|
| `INSERTING` | The trigger fired for an INSERT (or the insert branch of a MERGE) | All NULL | The row being inserted |
| `UPDATING` | The trigger fired for an UPDATE (or the update branch of a MERGE) | The row before the change | The row after the change |
| `DELETING` | The trigger fired for a DELETE | The row being deleted | All NULL |
The NULL columns in this table matter for every combined trigger. Reading :NEW.employee_id during a delete gives NULL, not an error, so a careless audit trigger silently records NULL ids for deleted rows.
The usual remedy is COALESCE(:NEW.employee_id, :OLD.employee_id), which picks whichever side has a value. You will see it in the audit trigger below.
A combined audit trigger
This trigger handles all three events and writes the old and new salary to an audit table:
CREATE OR REPLACE TRIGGER employees_aud
AFTER INSERT OR UPDATE OF salary OR DELETE ON employees
FOR EACH ROW
DECLARE
l_action VARCHAR2(6);
BEGIN
IF INSERTING THEN
l_action := 'INSERT';
ELSIF UPDATING THEN
l_action := 'UPDATE';
ELSE
l_action := 'DELETE';
END IF;
INSERT INTO employee_audit
(employee_id, action, old_salary, new_salary, changed_by, changed_at)
VALUES
(COALESCE(:NEW.employee_id, :OLD.employee_id),
l_action,
:OLD.salary,
:NEW.salary,
SYS_CONTEXT('USERENV', 'SESSION_USER'),
SYSTIMESTAMP);
END employees_aud;
/Three details are worth reading closely:
UPDATE OF salarynarrows only the update event. Every insert and every delete still fires the trigger. The column list does not apply to the other events.- The final branch is a plain
ELSE. It is safe here because only three events can fire the trigger. If you later add a fourth event to the triggering clause, this branch would mislabel it. UsingELSIF DELETINGand a finalELSEthat raises an error is stricter, and it catches that mistake. - The audit row is inserted by the trigger, so it commits or rolls back together with the employee change. That is usually what you want from an audit trail.
The decision flow looks like this:
Column-level checks with UPDATING('column')
UPDATING also accepts a column name. UPDATING('SALARY') is TRUE when the update touches the salary column. This lets one update trigger react differently to different columns:
CREATE OR REPLACE TRIGGER employees_touch
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
IF UPDATING('SALARY') OR UPDATING('DEPARTMENT_ID') THEN
:NEW.modified_at := SYSTIMESTAMP;
END IF;
END employees_touch;
/This example assumes employees has a modified_at TIMESTAMP column. Write the column name in uppercase inside single quotes, matching how Oracle stores an unquoted identifier.
The predicate tests what the statement said, not what changed. Consider this statement:
UPDATE employees SET salary = salary WHERE employee_id = 100;Salary appears in the SET clause, so UPDATING('SALARY') is TRUE even though the value is identical. The same is true for UPDATE OF salary: the trigger fires. If you need "the value actually changed", compare the values yourself:
IF UPDATING('SALARY') AND :NEW.salary <> :OLD.salary THEN
NULL; -- the value really changed
END IF;A null-safe form is DECODE(:NEW.salary, :OLD.salary, 0, 1) = 1, because <> against NULL yields neither TRUE nor FALSE.
Statement-level triggers can use predicates too
The predicates are not limited to row triggers. A statement-level trigger has no :OLD or :NEW, but it can still ask which event ran:
CREATE OR REPLACE TRIGGER employees_hours_chk
BEFORE INSERT OR UPDATE OR DELETE ON employees
BEGIN
IF TO_CHAR(SYSDATE, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') IN ('SAT', 'SUN') THEN
IF INSERTING THEN
RAISE_APPLICATION_ERROR(-20010, 'No inserts on weekends');
ELSIF UPDATING THEN
RAISE_APPLICATION_ERROR(-20011, 'No updates on weekends');
ELSE
RAISE_APPLICATION_ERROR(-20012, 'No deletes on weekends');
END IF;
END IF;
END employees_hours_chk;
/The trigger fires once per statement, however many rows the statement touches. Distinct error numbers per event help the calling application react.
Rules and limits
- Predicates work only in the trigger body. Using
INSERTINGin aWHENclause is a compile error. Express aWHENcondition with:NEWand:OLDvalues (written without a colon in theWHENclause), not with predicates. - A called procedure cannot see them. If your trigger calls a stored procedure, the predicates are not available there. Pass
INSERTING,UPDATING, andDELETINGas parameters, for example by passing the action string. - MERGE fires both sides. A MERGE that inserts some rows and updates others fires the insert and update triggers. Each row sees the predicate for the branch that processed it.
- Order inside a row is fixed per statement. One statement produces one event type. A trigger never sees
INSERTINGandUPDATINGboth TRUE at once.
Combined or separate triggers?
A combined trigger keeps related logic in one place. The cost is that every event pays for the whole body, and a bug in one branch can break compilation for all of them.
Prefer separate triggers when the events have little in common, or when you need different timing. A combined trigger has a single timing point, so it cannot be BEFORE for inserts and AFTER for deletes.
Use a combined trigger when the work is the same shape for every event, as in auditing. If you do split them, you can still control which fires first with the FOLLOWS clause, which a later chapter covers.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| NULL employee id in audit rows for deletes | Used `:NEW.employee_id` only | `COALESCE(:NEW.employee_id, :OLD.employee_id)` |
| PLS-00201 or compile error on `INSERTING` | Used it in a `WHEN` clause or a called procedure | Move the test into the trigger body |
| Trigger fires but nothing changed | `UPDATE OF col` or `UPDATING('COL')` is TRUE when the column is in SET, even with the same value | Compare `:NEW` and `:OLD` explicitly |
| Delete not audited | Triggering clause lists only INSERT and UPDATE | Add `OR DELETE` |
Exercise
A BEFORE INSERT OR UPDATE OR DELETE row trigger on employees must save the old last name to a history table on updates and deletes, but not on inserts. Which predicate-based condition should guard the history insert, and which correlation value supplies the name?
Show answer
Guard it with IF UPDATING OR DELETING THEN (or IF NOT INSERTING THEN), and take the name from :OLD.last_name. On an insert, :OLD is all NULL, so there is nothing to save. On both updates and deletes, :OLD holds the row's values before the change.
Exercise
An AFTER UPDATE OF salary trigger runs for the statement UPDATE employees SET salary = salary WHERE employee_id = 100. Does it fire, and how would you make the body act only when the salary really changes?
Show answer
Yes, it fires, because salary is in the SET clause and UPDATE OF (like UPDATING('SALARY')) looks at the statement, not at the values. To act only on a real change, test it inside the body, for example IF :NEW.salary <> :OLD.salary THEN ... or, to handle NULLs safely, IF DECODE(:NEW.salary, :OLD.salary, 0, 1) = 1 THEN ...