Sub topic 6
Limiting When a Trigger Fires: UPDATE OF and WHEN
This chapter assumes you can write a row-level trigger with CREATE OR REPLACE TRIGGER and that you can read :OLD and :NEW values. It uses the employees table from earlier chapters.
A trigger that fires on every UPDATE does work even when the update is irrelevant to it. Two clauses narrow that down. UPDATE OF filters on which columns the statement names. WHEN filters on the values in each row. They work at different levels, and they fail in different ways.
Why Narrow a Trigger?
A broad trigger has three costs:
- Each firing runs PL/SQL, which adds a context switch from SQL to PL/SQL for every affected row.
- Your logic must re-check inside the body whether the change matters.
- Unrelated updates can hit errors raised by the trigger body.
Moving the check into the trigger header lets Oracle skip the PL/SQL call entirely. For WHEN, the body never starts for rows that fail the condition.
UPDATE OF: Filtering by Column
UPDATE OF column_list makes the trigger fire only when the UPDATE statement names at least one listed column. Oracle decides this from the statement text, not from the data.
CREATE OR REPLACE TRIGGER employees_pay_bu
BEFORE UPDATE OF salary, commission_pct ON employees
FOR EACH ROW
BEGIN
:NEW.last_pay_change := SYSTIMESTAMP;
END employees_pay_bu;
/This example assumes employees has a last_pay_change TIMESTAMP column. The trigger behaves like this:
| Statement | Fires? |
|---|---|
| `UPDATE employees SET salary = 5000` | Yes |
| `UPDATE employees SET salary = salary` | Yes, because the column is named even though the value is unchanged |
| `UPDATE employees SET last_name = 'Kim'` | No |
| `UPDATE employees SET commission_pct = NULL, last_name = 'Kim'` | Yes, because one listed column appears |
| `INSERT INTO employees ...` | No, because `UPDATE OF` applies only to updates |
The third point is the most common surprise. Many application frameworks generate an UPDATE that sets every column on every save. With such a framework, UPDATE OF salary fires on every save, because salary is always in the SET list. When you need to react only to a changed value, add a WHEN clause.
You can combine UPDATE OF with other events, as in AFTER INSERT OR UPDATE OF salary OR DELETE. The column list then applies only to the update part. Inserts and deletes fire the trigger as usual.
WHEN: Filtering by Row Values
The WHEN clause takes a SQL condition that Oracle evaluates for each row. The body runs only if the condition is true. This example blocks salary decreases:
CREATE OR REPLACE TRIGGER employees_salary_chk
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
WHEN (NEW.salary < OLD.salary)
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased');
END employees_salary_chk;
/The two clauses work together here. UPDATE OF salary rules out statements that never touch salary, and WHEN rules out rows where the salary did not go down.
Rules for the WHEN Clause
NEWandOLDare written without a colon insideWHEN. Inside the PL/SQL body they need the colon (:NEW,:OLD).WHENis allowed only on row-level triggers. Adding it to a statement-level trigger raisesORA-04077.- The condition cannot contain a subquery or call a user-defined PL/SQL function. It is limited to column references, literals, operators, and built-in SQL functions.
- If you rename the correlation names with
REFERENCING NEW AS n OLD AS o, use those names inWHEN, for exampleWHEN (n.salary < o.salary). WHENis not available inINSTEAD OFtriggers on views.
Evaluation Flow
Oracle applies the filters in a fixed order. The diagram shows how one UPDATE statement reaches the trigger body.
The first check happens once per statement, from its text. The second check happens once per row, from the values. A trigger without WHEN skips the second check and runs for every row.
The NULL Trap in WHEN
WHEN runs the body only when the condition is true. Comparisons with NULL are unknown, which counts as not true. This causes a quiet failure:
-- Bug: misses changes to or from NULL
CREATE OR REPLACE TRIGGER employees_dept_chg_bad
AFTER UPDATE OF department_id ON employees
FOR EACH ROW
WHEN (NEW.department_id <> OLD.department_id)
BEGIN
NULL;
END;
/If an employee moves from department 10 to NULL, then NEW.department_id <> OLD.department_id is unknown. The trigger does not fire, and the change goes unrecorded. A null-safe version checks the NULL cases explicitly:
CREATE TABLE dept_transfer_log (
employee_id NUMBER,
old_dept NUMBER,
new_dept NUMBER,
moved_at TIMESTAMP
);
CREATE OR REPLACE TRIGGER employees_dept_chg
AFTER UPDATE OF department_id ON employees
FOR EACH ROW
WHEN ( NEW.department_id <> OLD.department_id
OR (NEW.department_id IS NULL AND OLD.department_id IS NOT NULL)
OR (NEW.department_id IS NOT NULL AND OLD.department_id IS NULL))
BEGIN
INSERT INTO dept_transfer_log
(employee_id, old_dept, new_dept, moved_at)
VALUES
(:NEW.employee_id, :OLD.department_id, :NEW.department_id, SYSTIMESTAMP);
END employees_dept_chg;
/Now the trigger fires for a move between departments, a move to NULL, and a move from NULL. An update that sets the same department again is skipped, even though the column appears in the SET list.
WHEN with Multiple Events
When one trigger handles INSERT OR UPDATE, remember that OLD values are all NULL for an insert. A condition like NEW.salary > OLD.salary is unknown for every inserted row, so the trigger never fires on inserts. Two ways to handle this:
- Write the condition so it covers the insert case, for example
WHEN (OLD.salary IS NULL OR NEW.salary > OLD.salary). - Split the work into separate triggers, one per event, each with its own
WHEN.
The second option is usually clearer. The INSERTING, UPDATING, and DELETING predicates (covered in the previous chapter) only work inside the body, after WHEN has already filtered the row. You cannot use them in WHEN.
Choosing Between the Two Clauses
| Question | UPDATE OF | WHEN |
|---|---|---|
| What does it inspect? | Column names in the `SET` list | Row values (`OLD` and `NEW`) |
| When is it checked? | Once per statement | Once per row |
| Works on statement-level triggers? | Yes | No (ORA-04077) |
| Detects unchanged values? | No | Yes, if you compare `NEW` and `OLD` |
| Applies to INSERT or DELETE? | No | Yes, row-level triggers for any event |
Use UPDATE OF as a cheap first filter. Add WHEN when the real condition depends on values.
Checking That a Trigger Fires
Before trusting a narrowed trigger, run a test that should fire it and one that should not. This sketch uses the salary trigger from earlier:
SET SERVEROUTPUT ON
BEGIN
UPDATE employees SET salary = salary + 100 WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Raise accepted');
UPDATE employees SET salary = salary - 100 WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Not reached');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Blocked: ' || SQLERRM);
ROLLBACK;
END;
/The first update passes the WHEN check and is accepted. The second raises ORA-20001, which the handler prints. Also test an update that changes only last_name. It must succeed, because UPDATE OF salary prevents the trigger from firing at all.
Exercise
A trigger is defined as AFTER UPDATE OF status ON orders FOR EACH ROW WHEN (NEW.status <> OLD.status). The status column allows NULL. Name two situations where the trigger does not fire even though the status "changed", and rewrite the WHEN clause so it fires in both.
Show answer
(1) Status changes from 'OPEN' to NULL. (2) Status changes from NULL to 'OPEN'. In both, the comparison is unknown, not true. Fixed clause: WHEN (NEW.status <> OLD.status OR (NEW.status IS NULL AND OLD.status IS NOT NULL) OR (NEW.status IS NOT NULL AND OLD.status IS NULL)). An update such as SET status = status still fires nothing, because the values are equal.
Exercise
You add WHEN (NEW.salary > 10000) to a statement-level trigger (no FOR EACH ROW). What happens, and how do you fix it?
Show answer
Oracle rejects the trigger with ORA-04077, because WHEN is allowed only on row-level triggers. Add FOR EACH ROW to make it a row trigger, or remove WHEN and do the check differently at statement level (for example, in a compound trigger that collects rows).