Sub topic 4
Reading and Changing Row Values with `:OLD` and `:NEW`
This chapter assumes you know basic SQL, PL/SQL variables and IF statements, tables, sequences, views, and transaction control with COMMIT and ROLLBACK.
A row-level Oracle trigger can inspect the row affected by an INSERT, UPDATE, or DELETE. Oracle exposes the row through two correlation records:
:OLDcontains the values before the DML operation.:NEWcontains the values after the operation, or the values that will be stored.
The colon is required in the trigger body. These values are available only in a row-level trigger, not a statement-level trigger.
Which Values Are Available?
| DML operation | `:OLD` | `:NEW` |
|---|---|---|
| `INSERT` | Not meaningful | New row values |
| `UPDATE` | Previous row values | New row values |
| `DELETE` | Deleted row values | Not meaningful |
For example, an update can compare a salary before and after the change:
CREATE OR REPLACE TRIGGER employees_salary_audit
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_salary_audit
(employee_id, old_salary, new_salary, changed_at)
VALUES
(:OLD.employee_id, :OLD.salary, :NEW.salary, SYSTIMESTAMP);
END employees_salary_audit;
/The trigger reads both versions of the row. Because it is an AFTER trigger, the update has already passed its normal processing. It records the change in the same transaction as the update.
Changing `:NEW` in a `BEFORE` Trigger
A BEFORE row trigger can assign values to :NEW. This lets the database normalize input or calculate derived values before Oracle stores the row.
CREATE OR REPLACE TRIGGER employees_normalize_biu
BEFORE INSERT OR UPDATE OF last_name ON employees
FOR EACH ROW
BEGIN
IF :NEW.last_name IS NOT NULL THEN
:NEW.last_name := UPPER(TRIM(:NEW.last_name));
END IF;
IF INSERTING AND :NEW.created_at IS NULL THEN
:NEW.created_at := SYSTIMESTAMP;
END IF;
END employees_normalize_biu;
/An insert such as last_name = ' chen ' is stored as CHEN. The trigger can change :NEW, but it cannot change :OLD. An AFTER row trigger can read :NEW but should not be used to assign it.
Common Errors
Remember these rules:
- Do not reference
:OLDas the new value during an insert. - Do not reference
:NEWas the deleted value during a delete. - Do not omit the colon in the trigger body.
- Do not assign to
:OLD. - Do not assign to
:NEWfrom a statement-level orAFTERtrigger. - A trigger that changes
:NEWdoes not commit the transaction.
The :OLD and :NEW records contain column values, so use :NEW.salary, not simply :NEW.
Exercise
Which correlation value should a BEFORE UPDATE trigger use when it needs the salary before and after the change?
Show answer
Use :OLD.salary for the previous value and :NEW.salary for the incoming value.