Can anyone help me understand when to use :NEW
and :OLD
in PLSQL blocks, I\'m finding it very difficult to understand their usage.
It's very simple
If Insert :old = NULL and :New = New Inserted Value
If Update :Old = Value already in the table :New = Updated Value in the Table
If Delete :Old = Value before deletion :New = NULL
IN other Words
For an INSERT trigger, OLD contains no values, and NEW contains the new values.
For an UPDATE trigger, OLD contains the old values, and NEW contains the new values.
For a DELETE trigger, OLD contains the old values, and NEW contains no values.
Example:
CREATE OR REPLACE TRIGGER update_name_view_trigger
INSTEAD OF UPDATE ON emp_locations
BEGIN
UPDATE employees SET
first_name = substr( :NEW.name, instr( :new.name, ',' )+2),
last_name = substr( :NEW.name, 1, instr( :new.name, ',')-1)
WHERE employee_id = :OLD.employee_id;
END;
:OLD and :NEW are variables of type Record and is identical in columns to the table row on which the trigger is fired. They are only available for row level triggers. Since triggers are fired on a predefined event automatically so :OLD and :NEW also get their value automatically . As the name suggests , :OLD will have the complete row values existing in table ( i.e has the existing values in case of update and delete ) and :NEW will have new values for that rows ( i.e. has the row value in case of update and insert ).
In simple way,
Trigger will fire when you manipulate data into table. so while trigger invoke, you have both value. one is referring to old data value and one is the new data value which you recently update/delete/insert. in-case of
insert- old value would be null and new value contain some value update - old and new both have some value delete - old has value but new will not contain value.
so by using :OLD and :NEW, you can insert/update other table where you want to maintain your history or based on :OLD or :NEW value you can insert/update some other dependent table.
Hopefully this helps you..
A simple example that shows the use of old and new using triggers
CREATE TABLE emp_log(
emp_id NUMBER;
updated_by DATE,
new_salary VARCHAR2(15),
Action VARCHAR2(20));
CREATE OR REPLACE TRIGGER log_sal
AFTER UPDATE OF sal on emp
FOR EACH ROW
BEGIN
INSERT INTO emp_log( emp_id, updated_by, new_salary, Action)
VALUES(:NEW.empno, USER, :NEW.sal, 'New salary');
END;
/
:New and :Old Value can be differentiated in DML Statements .
Insert -- :Old = NULL :New= Inserted new value
Update -- :Old = Value present in table before the Update statement Triggered :New = Given new value to Update
Delete -- :Old = Value before deletion :New = NULL
:old is your old value :new is your new value,
it is used alot in triggers for example with Creation_Date & Modified_By fields