PL/SQL Triggers: Mastering Database Events in Oracle

beginner
10 min

PL/SQL Triggers: Mastering Database Events in Oracle

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!

Understanding PL/SQL Triggers

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.

Trigger Types

Oracle supports three types of triggers:

  1. DML Triggers: React to Data Manipulation Language (DML) events like INSERT, UPDATE, and DELETE.
  2. DDL Triggers: Respond to Data Definition Language (DDL) events, such as CREATE, ALTER, and DROP.
  3. DBMS Triggers: Handle other miscellaneous database events, such as logging, auditing, and database link events.

Creating a Simple DML Trigger

Let's create a DML trigger that logs any insertion into a table.

sql
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.

Testing and Querying the Trigger

Now, let's insert a new employee and verify the log entry.

sql
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.

Quiz

Quick Quiz
Question 1 of 1

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! šŸš€