NEW and OLD Context Variables
Go Up to The Trigger Body
Triggers can use two context variables, OLD, and NEW. The OLD context variable refers to the current or previous values in a row being updated or deleted. OLD is not used for inserts. NEW refers to a new set of INSERT or UPDATE values for a row. NEW is not used for deletes. Context variables are often used to compare the values of a column before and after it is modified.
The syntax for context variables is as follows:
NEW.column OLD.column
where <column> is any column in the affected row. Context variables can be used anywhere a regular variable can be used.
New values for a row can only be altered before actions. A trigger that fires after INSERT and tries to assign a value to NEW.<column> will have no effect. The actual column values are not altered until after the action, so triggers that reference values from their target tables will not see a newly inserted or updated value unless they fire after UPDATE or INSERT.
For example, the following trigger fires after the EMPLOYEE table is updated, and compares an employee’s old and new salary. If there is a change in salary, the trigger inserts an entry in the SALARY_HISTORY table.
CREATE TRIGGER SAVE_SALARY_CHANGE FOR EMPLOYEE AFTER UPDATE AS BEGIN IF (old.salary <> new.salary) THEN INSERT INTO SALARY_HISTORY (EMP_NO, CHANGE_DATE, UPDATER_ID, OLD_SALARY, PERCENT_CHANGE) VALUES (old.emp_no, 'now', USER, old.salary, (new.salary - old.salary) * 100 / old.salary); END ;
- Note: Context variables are never preceded by a colon, even in SQL statements.