OLD
OLD is a keyword in SQL that is primarily used in triggers. It allows for referencing the values of the columns of a row before it was updated. In the context of a Delete operation, OLD is used to reference the values of the columns of a row before it's deleted.
Example
Output
Explanation
In this example, a trigger named ‘example_trigger’ is created on ‘student_table’. This trigger fires before an update operation on the ‘student_table’. If the new age value in the update statement is less than the old age value, the update operation is aborted and a message ‘Age can not be reduced’ is displayed. The ‘OLD’ keyword is used to refer to column values as they were before the UPDATE operation.
Example
Output
Explanation
The sample code demonstrates a trigger in SQL Server, which executes when an update event takes place on ‘sample_table’. The OLD statement is used to fetch the old value of ‘column_name’, that was present before the update operation. The old value is stored in the local variable ‘@old_val’, and then printed. Note however, that ‘OLD.column_name’ syntax as used in this example, works in MySQL, but is not directly applicable in SQL Server. In SQL Server, the ‘deleted’ pseudo table is used instead to access the old records.
Example
Output
Explanation
In this example, a trigger is created with the name before_employee_update
which fires before any update operation on the employee
table. During the trigger action, it outputs the old salary of the employee using :OLD.salary
statement, which refers to the state of the row before it was updated.