What is a Trigger in PL/SQL

π What is a Trigger in PL/SQL?
A Trigger in PL/SQL is a database object that automatically executes when a specific event occurs on a table or view, such as INSERT, UPDATE, or DELETE.
Unlike procedures or functions, triggers fire implicitlyβyou donβt call them manually.
πΉ Why Triggers are Used
β Enforce business rules β Automatically validate data β Maintain audit logs (who changed what & when) β Prevent invalid operations β Maintain derived or dependent data
πΉ Types of Triggers
πΈ DML Triggers β INSERT, UPDATE, DELETE
πΈ BEFORE Trigger β Executes before the DML operation
πΈ AFTER Trigger β Executes after the DML operation
πΈ Row-Level Trigger β Executes for each row (FOR EACH ROW)
πΈ Statement-Level Trigger β Executes once per SQL statement
πΈ INSTEAD OF Trigger β Used with views
πΉ Simple Example
CREATE OR REPLACE TRIGGER trg_before_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
:NEW.created_date := SYSDATE;
END;
π This trigger automatically sets the created_date whenever a new employee record is inserted.
β οΈ Best Practices
β Avoid heavy business logic in triggers β Donβt use triggers where procedures can handle logic clearly β Keep triggers simple and efficient
π― Interview-Oriented Points
* Triggers are **event-driven**, not user-driven
* They execute **automatically**
* :NEWand:OLD are used in row-level triggers
* Cannot use COMMITorROLLBACK inside a trigger
* Triggers can impact performance if misused