Welcome to our comprehensive guide on PL/SQL Triggers! In this tutorial, we'll dive deep into the world of database events in Oracle, learning how to create, manage, and utilize PL/SQL triggers for practical applications. Let's get started!
A trigger in Oracle is a special kind of stored procedure that automatically responds to specific events, such as data modifications, within a database. Triggers are primarily written in PL/SQL, making them a powerful tool for data integrity and workflow automation.
š” Pro Tip: Triggers help enforce rules on your database and maintain data consistency, making them essential for real-world applications.
Oracle supports three types of triggers:
INSERT, UPDATE, and DELETE.CREATE, ALTER, and DROP.Let's create a DML trigger that logs any insertion into a table.
CREATE TABLE Employees (
Employee_ID NUMBER PRIMARY KEY,
First_Name VARCHAR2(50),
Last_Name VARCHAR2(50)
);
CREATE OR REPLACE TRIGGER log_insert
AFTER INSERT ON Employees
FOR EACH ROW
BEGIN
INSERT INTO Logs (Action, Timestamp, Employee_ID)
VALUES ('INSERT', SYSDATE, :NEW.Employee_ID);
END;š Note: In the above example, :NEW refers to the new row that has been inserted into the Employees table.
Now, let's insert a new employee and verify the log entry.
INSERT INTO Employees (Employee_ID, First_Name, Last_Name)
VALUES (101, 'John', 'Doe');
SELECT * FROM Logs;After running the above commands, you should see the new log entry in the Logs table.
What is the main purpose of a trigger in Oracle?
As you delve deeper into PL/SQL triggers, you'll discover their vast potential for data validation, auditing, and maintaining data consistency. Happy coding! š