Sub topic 5
One Trigger, Several Events: INSERTING, UPDATING, DELETING
Prerequisites
This chapter assumes that you know basic SQL data changes, PL/SQL IF statements, row-level triggers, and the :OLD and :NEW correlation values.
A trigger can respond to more than one data manipulation language (DML) event. DML events are INSERT, UPDATE, and DELETE. Inside the trigger body, conditional predicates identify which event caused the trigger to run:
INSERTINGis true during an insert.UPDATINGis true during an update.DELETINGis true during a delete.
This pattern is useful when several events need the same surrounding logic, such as writing an audit record.
How Event Predicates Work
The predicates are PL/SQL conditions. They do not use parentheses and do not compare column values. Oracle sets the appropriate predicate to true for the current firing event.
| DML event | True predicate | Available row values |
|---|---|---|
| `INSERT` | `INSERTING` | `:NEW` |
| `UPDATE` | `UPDATING` | `:OLD` and `:NEW` |
| `DELETE` | `DELETING` | `:OLD` |
For an insert, the old row does not exist, so :OLD values are null. For a delete, the new row does not exist, so :NEW values are null. An update has both versions.
The trigger event list uses OR. The trigger below runs after an insert, a salary update, or a delete:
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;
/UPDATE OF salary narrows the update event. The trigger fires when the salary column appears in the UPDATE statement. It does not require the salary value to change. For example, UPDATE employees SET salary = salary still references the column and can fire the trigger.
COALESCE chooses the first non-null value. It therefore gets the employee ID from :NEW for an insert and from :OLD for a delete. During an update, both values normally identify the same row.
Understanding Execution
The audit insert runs in the same transaction as the original employee change. If the original statement is rolled back, the audit row is rolled back too.
Common Errors
- Referencing
:NEWas though it contains a new row duringDELETE. - Referencing
:OLDas though it contains an old row duringINSERT. - Assuming
UPDATE OF salarymeans the value changed. - Forgetting that a row-level trigger runs once for every affected row.
Exercise
During which events are both :OLD.salary and :NEW.salary available, and which predicate identifies that event?
Show answer
Both are available during an UPDATE, identified by the UPDATING predicate.