Database Trigger (All Types: Row level and Statement level triggers, Before and After Triggers)
Problem Statement:
Write a database trigger on Library table. The System should keep track of the records that are being updated or deleted. The old value of updated or deleted records should be added in Library_Audit table.
Note: Instructor will Frame the problem statement for writing PL/SQL block for all types of Triggers in line with above statement.
"Write a database trigger on the Library table that maintains an audit log. Whenever a record is updated or deleted, the old values of that record should be inserted into the Library_Audit table. The trigger should differentiate between update and delete operations and store additional details like the type of operation and the timestamp."
Let's Study First What is Trigger? Why do we need Trigger? How to implement Trigger?
Note: Instructor will Frame the problem statement for writing PL/SQL block for all types of Triggers in line with above statement.
"Write a database trigger on the Library table that maintains an audit log. Whenever a record is updated or deleted, the old values of that record should be inserted into the Library_Audit table. The trigger should differentiate between update and delete operations and store additional details like the type of operation and the timestamp."
let's understand what we want to do here in this.
You have a Library table in a database.
Whenever a record in this table is UPDATED or DELETED, you don’t want to lose the old information.
So, you need to:
Write a database trigger that automatically captures the old values before they are changed or removed.
Insert those old values into another table called Library_Audit (this act like a log/history table).
This way:
If someone updates a book’s details → the previous details are saved in Library_Audit.
If someone deletes a book record → the deleted record is also saved in Library_Audit.
But why this is needed?
Audit trail: Helps to keep track of who changed or removed data.
Data recovery: If someone deletes a row by mistake, you still have the backup in Library_Audit.
Accountability: Ensures transparency in changes to critical data.
Let's start the Implementation part:
Since we want all types of triggers, we’ll cover:
1. Row-level trigger
2. Statement-level trigger
3. BEFORE trigger
4. AFTER trigger
5. INSTEAD OF trigger (used for views)
First, we have to create two tables 1. Library and 2. Library_Audit common for all types of triggers.