Can anyone help me understand when to use :NEW
and :OLD
in PLSQL blocks, I\'m finding it very difficult to understand their usage.
:old and :new are pseudorecords referred to access row level data when using row level trigger.
For Below operation, respective old and new values:
Eg:
CREATE OR REPLACE TRIGGER get_dept
BEFORE DELETE OR INSERT OR UPDATE ON employees
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT('Old Dept= ' || :OLD.dept|| ', ');
DBMS_OUTPUT.PUT('New Dept= ' || :NEW.dept );
END;
Triggering Statement:
UPDATE employees
SET dept ='Accounts'
WHERE empno IN (101 ,105);
New and Old more relevant for update operation inside a trigger, to fetch old value of field use old and for recent value use new
You normally use the terms in a trigger using :old
to reference the old value and :new
to reference the new value.
Here is an example from the Oracle documentation linked to above
CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :new.sal - :old.sal;
dbms_output.put('Old salary: ' || :old.sal);
dbms_output.put(' New salary: ' || :new.sal);
dbms_output.put_line(' Difference ' || sal_diff);
END;
In this example the trigger fires BEFORE DELETE OR INSERT OR UPDATE
:old.sal
will contain the salary prior to the trigger firing and :new.sal
will contain the new value.
You can use :OLD
while working on after/before update 100% of time
:NEW
is a record of the new value added by (insert or update)
:OLD
is for old values.
Without them, triggers are useless
:new is the new value - After the trigger is fired this is the value of the column :old is the old value - After the trigger is fired this value is replaced with :new value
:new means the new value your are trying to insert :old means the existing value in database