PL/SQL Row-Level Triggers
Last Updated :
13 Sep, 2024
In PL/SQL, triggers are special stored procedures that automatically execute in response to specific events on a table or view. Among these, row-level triggers are particularly useful for enforcing business rules, maintaining data integrity, and automating tasks.
This article explores row-level triggers with practical examples and explanations.
What are Row-Level Triggers?
Row-level triggers execute once for each row affected by an INSERT, UPDATE, or DELETE operation. This makes them ideal for performing actions specific to each row being processed.
Syntax of Row-Level Triggers
The basic syntax for creating a row-level trigger in PL/SQL is:
CREATE [OR REPLACE] TRIGGER trigger_name
AFTER | BEFORE [INSERT | UPDATE | DELETE] ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic here
END;
Parameters:
- AFTER | BEFORE: Specifies whether the trigger should fire before or after the triggering event.
- INSERT | UPDATE | DELETE: Specifies the DML operation that activates the trigger.
- FOR EACH ROW: Indicates that the trigger is row-level, meaning it fires for each row affected by the DML operation.
Examples of PL/SQL Row-Level Triggers
Example 1: Auditing Changes in a Table
Suppose you have an employees table and want to track any changes to employee salaries. You can create a row-level trigger that logs these changes into an employee_audit table.
Step 1: Create the employees Table
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50),
salary NUMBER,
last_modified DATE
);
Step 2: Create the employee_audit Table
CREATE TABLE employee_audit (
audit_id NUMBER PRIMARY KEY,
emp_id NUMBER,
old_salary NUMBER,
new_salary NUMBER,
change_date DATE
);
Step 3: Create the Trigger
CREATE OR REPLACE TRIGGER trg_audit_salary_changes
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (audit_id, emp_id, old_salary, new_salary, change_date)
VALUES (employee_audit_seq.NEXTVAL, :OLD.emp_id, :OLD.salary, :NEW.salary, SYSDATE);
END;
Explanation: This trigger logs the employee ID, old salary, new salary, and the date of change in the employee_audit table whenever an employee's salary is updated.
Testing Example 1:
Insert Initial Data into employees:
INSERT INTO employees (emp_id, emp_name, salary, last_modified) VALUES (1, 'Alice', 50000, SYSDATE);
INSERT INTO employees (emp_id, emp_name, salary, last_modified) VALUES (2, 'Bob', 45000, SYSDATE);
INSERT INTO employees (emp_id, emp_name, salary, last_modified) VALUES (3, 'Charlie', 60000, SYSDATE);
Update Salary to Trigger the Audit:
UPDATE employees SET salary = 55000 WHERE emp_id = 1;
Expected Output:
- The employees table will show Alice's updated salary.
- The employee_audit table will have a new record logging the change:
SELECT * FROM employee_audit;
Output:
AUDIT_ID | EMP_ID | OLD_SALARY | NEW_SALARY | CHANGE_DATE
---------|--------|------------|------------|-------------
1 | 1 | 50000 | 55000 | 23-AUG-2024
Example 2: Enforcing Business Rules
Next, we enforce a business rule that prevents employees from having a negative salary.
CREATE OR REPLACE TRIGGER trg_no_negative_salary
BEFORE INSERT OR UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be negative');
END IF;
END;
Explanation: This trigger checks the new salary value before an insert or update. If the salary is negative, an error is raised, preventing the operation.
Testing Example 2:
Attempt to Insert an Employee with a Negative Salary:
INSERT INTO employees (emp_id, emp_name, salary, last_modified) VALUES (4, 'David', -10000, SYSDATE);
Output:
The operation will fail, and you will receive the following error message: ORA-20001: Salary cannot be negative.
Example 3: Automatically Updating a Timestamp
To maintain a last modified timestamp for each row in a table, you can use a row-level trigger.
CREATE OR REPLACE TRIGGER trg_update_timestamp
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
:NEW.last_modified := SYSDATE;
END;
Explanation: This trigger automatically updates the last_modified column to the current date and time whenever a row in the employees table is updated.
Testing Example 3:
Update an Employee's Name:
UPDATE employees SET emp_name = 'Alicia' WHERE emp_id = 1;
Output:
The employees table will show the updated name and the last_modified timestamp:
SELECT * FROM employees WHERE emp_id = 1;
EMP_ID | EMP_NAME | SALARY | LAST_MODIFIED
-------|----------|--------|--------------
1 | Alicia | 55000 | 23-AUG-2024
Conclusion
Row-level triggers in PL/SQL are useful tools that automatically perform tasks whenever data is added, updated, or deleted in a table. They work on each individual row, allowing you to enforce rules and ensure data accuracy. By understanding how to use these triggers, you can make your PL/SQL applications more reliable and efficient, handling data operations with greater control and precision.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read