Sub topic 4
Reading and Changing Row Values with :OLD and :NEW
This chapter assumes you can write basic PL/SQL blocks and have seen the CREATE OR REPLACE TRIGGER syntax from the previous chapter. You should also know the difference between statement-level and row-level triggers. Correlation values exist only in row-level triggers, so every trigger here uses FOR EACH ROW.
What :OLD and :NEW Are
A row-level trigger runs once for each row that the triggering statement affects. For each row, Oracle gives the trigger two pseudorecords:
:OLDholds the column values the row had before the statement changed it.:NEWholds the column values the row will have after the statement.
A pseudorecord looks like a PL/SQL record, and you read a column with :NEW.salary. It is not a real variable. You can't declare one or use it outside a row trigger.
Which values exist depends on the triggering event:
| Event | :OLD | :NEW |
|---|---|---|
| INSERT | All columns are NULL | The values being inserted |
| UPDATE | The values before the update | The values after the update. Columns not in the SET list keep their old values. |
| DELETE | The values of the row being removed | All columns are NULL |
Nothing raises an error when you read a value that doesn't apply. :OLD.salary in an insert trigger is simply NULL. A trigger that handles several events must therefore use the INSERTING, UPDATING and DELETING predicates before it relies on either side.
Where You Can Change Values
You can assign to :NEW only in a BEFORE row trigger. Oracle fires that trigger before it stores the row, so whatever is in :NEW when the trigger finishes is what gets written.
Two rules follow from this:
- In an AFTER row trigger, assigning to
:NEWfails when the trigger is compiled, with ORA-04084. The row is already stored, so the assignment would do nothing. - You can never assign to
:OLD. It is read only in every trigger. Attempting it raises ORA-04085.
Use a BEFORE trigger when you want to change what is stored. Use an AFTER trigger when you only need to react to the stored values, for example to write an audit row.
A Worked Example
The following table and trigger clean up a name and stamp each row. When the salary changes, the trigger also compares :OLD and :NEW.
CREATE TABLE emp_demo (
employee_id NUMBER PRIMARY KEY,
last_name VARCHAR2(50),
salary NUMBER(8,2),
updated_at TIMESTAMP
);
CREATE OR REPLACE TRIGGER emp_demo_biu
BEFORE INSERT OR UPDATE ON emp_demo
FOR EACH ROW
BEGIN
:NEW.last_name := UPPER(TRIM(:NEW.last_name));
:NEW.updated_at := SYSTIMESTAMP;
IF UPDATING AND :NEW.salary <> :OLD.salary THEN
DBMS_OUTPUT.PUT_LINE('Salary ' || :OLD.salary || ' -> ' || :NEW.salary);
END IF;
END emp_demo_biu;
/Run it with a short test:
SET SERVEROUTPUT ON
INSERT INTO emp_demo (employee_id, last_name, salary)
VALUES (1, ' smith ', 4000);
UPDATE emp_demo SET salary = 4500 WHERE employee_id = 1;
SELECT employee_id, last_name, salary FROM emp_demo;The output shows Salary 4000 -> 4500. The query returns the last name as SMITH, even though the insert supplied ' smith '. The caller never sees the cleanup code, and no application can skip it.
Check the comparison in the IF. :NEW.salary <> :OLD.salary is never true when either side is NULL, so a change from NULL to 5000 is missed. When NULL is a valid value, test it explicitly:
IF :NEW.salary <> :OLD.salary
OR (:NEW.salary IS NULL AND :OLD.salary IS NOT NULL)
OR (:NEW.salary IS NOT NULL AND :OLD.salary IS NULL) THEN
NULL; -- the value changed
END IF;Colons in the Body, No Colons in WHEN
Inside the PL/SQL body, you write :OLD and :NEW with a leading colon, because they are bind-like references. In the WHEN clause, the colon is not allowed. The earlier salary trigger used WHEN (NEW.salary < OLD.salary). The same condition inside the body would be IF :NEW.salary < :OLD.salary.
The WHEN condition is checked before the trigger body starts. If it is false, Oracle skips the body for that row. This is cheaper than starting the body and exiting early with an IF.
Renaming the Pseudorecords with REFERENCING
The REFERENCING clause gives the pseudorecords other names. This is useful when a table has a column called old or new, or when a trigger is hard to read with the default names. The clause goes before FOR EACH ROW.
CREATE OR REPLACE TRIGGER emp_demo_ref
BEFORE UPDATE OF salary ON emp_demo
REFERENCING OLD AS prev NEW AS curr
FOR EACH ROW
WHEN (curr.salary > prev.salary * 2)
BEGIN
RAISE_APPLICATION_ERROR(
-20010,
'Raise from ' || :prev.salary || ' to ' || :curr.salary || ' exceeds 100 percent');
END emp_demo_ref;
/The new names follow the same rules as before. Use a colon in the body (:prev, :curr) and no colon in WHEN. Both triggers now fire on updates to emp_demo. If you test this one, bear in mind that its error stops any update that more than doubles a salary.
What Each Event Can See
The predicates from the next chapter combine with :OLD and :NEW to handle every event in one trigger. The sketch below shows which side to read for each event.
CREATE OR REPLACE TRIGGER emp_demo_ad
AFTER INSERT OR UPDATE OR DELETE ON emp_demo
FOR EACH ROW
DECLARE
l_id emp_demo.employee_id%TYPE;
BEGIN
IF DELETING THEN
l_id := :OLD.employee_id; -- :NEW is all NULL on delete
ELSE
l_id := :NEW.employee_id; -- :OLD is all NULL on insert
END IF;
DBMS_OUTPUT.PUT_LINE('Row touched: ' || l_id);
END emp_demo_ad;
/COALESCE(:NEW.employee_id, :OLD.employee_id) does the same job in a single expression, as the audit trigger in a later chapter does. It works because exactly one side is NULL on an insert or delete. Be careful with it when the column itself can be NULL on a real row.
Gotchas
- UPDATE OF fires on assignment, not on change.
UPDATE emp_demo SET salary = salarynames the column, so a trigger declaredUPDATE OF salaryfires, and:OLD.salaryequals:NEW.salary. Compare the two values if you only care about real changes. - Whole-row updates make every column look assigned. Some tools issue
UPDATE ... SETfor every column. A trigger relying onUPDATE OFthen fires on every update, so check the values as well. - Changing :NEW in a DELETE trigger does nothing. All
:NEWcolumns are NULL and no row is stored. - Primary keys. Changing
:NEW.employee_idin a BEFORE UPDATE trigger is legal, but it rewrites the key. Foreign keys that reference it may then fail. Use it with care. - Read the table, and you hit ORA-04091.
:OLDand:NEWare safe because they hold copies of the row. A query on the same table inside a row trigger is not safe. The mutating table error, covered later, explains why. - Large objects. Rules for LOB and
LONGcolumns in pseudorecords differ from ordinary columns. Check the Oracle documentation before using them in a trigger.
Summary of the Rules
- Row-level triggers only. Statement triggers have no
:OLDor:NEW. - INSERT has no usable
:OLD. DELETE has no usable:NEW. UPDATE has both. - Only BEFORE row triggers can assign to
:NEW. No trigger can assign to:OLD. - Use the colon in the body and omit it in
WHEN. REFERENCINGrenames the pseudorecords but does not change what they hold.- NULL comparisons on either side need explicit
IS NULLtests.
Exercise
A table orders has columns order_id, status and shipped_at. Write a BEFORE UPDATE OF status row trigger that sets shipped_at to SYSTIMESTAMP only when the status changes from something else to 'SHIPPED'. Use a WHEN clause so the body does not start for other updates. Which pseudorecord do you assign to, and why can't this be an AFTER trigger?
Show answer
CREATE OR REPLACE TRIGGER ordersshipbu BEFORE UPDATE OF status ON orders FOR EACH ROW WHEN (NEW.status = 'SHIPPED' AND (OLD.status IS NULL OR OLD.status <> 'SHIPPED')) BEGIN :NEW.shippedat := SYSTIMESTAMP; END ordersshipbu; / You assign to :NEW.shippedat. Oracle stores the row after a BEFORE trigger, so the assignment becomes part of the stored row. In an AFTER trigger the row is already stored, so assigning to :NEW is not allowed (ORA-04084). The WHEN clause uses NEW and OLD without colons, and it includes the IS NULL test so a first-time status of 'SHIPPED' is also caught.
Exercise
What values do :OLD.lastname and :NEW.lastname have in a row trigger that fires for DELETE FROM empdemo WHERE employeeid = 1, when the stored last name is 'SMITH'?
Show answer
:OLD.lastname is 'SMITH' and :NEW.lastname is NULL. On a delete, :OLD holds the row being removed and every column of :NEW is NULL.