sofiDev img

Mobashshir Hasan

What is a Trigger in PL/SQL

javascript image


πŸ“Œ 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