Skip to content

SQL Triggers

A trigger is a stored block of PL/SQL code that automatically executes (fires) in response to specific events on a table or view.

Objectives of Triggers:

  • Monitor and control changes to a database.

  • Automatically execute predefined logic when certain operations occur (INSERT, UPDATE, DELETE).

Components of a Trigger

Every trigger has three core components:

ComponentDescription
EventThe DML operation that fires the trigger (INSERT, UPDATE, DELETE)
ConditionOptional WHEN clause that determines whether the trigger action should be executed
ActionThe SQL or PL/SQL block that runs when the event and condition are satisfied

Why Use Triggers?

  • Enforce complex business rules

  • Automatically maintain derived attributes (e.g., totals, averages)

  • Perform data validation before accepting changes

  • Maintain audit trails of database operations

  • Prevent invalid transactions

  • Execute cascading changes across related tables

Types of Triggers

Trigger TypeDescription
BEFOREExecutes before the triggering event
AFTERExecutes after the triggering event
INSTEAD OFExecutes instead of the triggering event (used for views)
Row-levelExecutes once for each affected row
Statement-levelExecutes once per triggering statement, regardless of the number of rows affected

Trigger Syntax

sql
CREATE [OR REPLACE] TRIGGER trigger_name
	{BEFORE | AFTER | INSTEAD OF}
	{INSERT [OR] | UPDATE [OR] | DELETE}
	[OF column_name] -- Only for UPDATE triggers
	ON table_name
	[REFERENCING OLD AS o NEW AS n] 
		-- Optional aliases for :OLD and :NEW
	[FOR EACH ROW] -- Row-level trigger
	[WHEN (condition)]  -- Optional
BEGIN
  -- SQL / PL/SQL statements
END;
  • :OLD — value before the DML operation

  • :NEW — value after the DML operation (Available only in row-level triggers)

Example 1: Age Validation Before Insert/Update

Trigger to prevent inserting or updating an employee whose age is above 60.

sql
CREATE OR REPLACE TRIGGER age_violation
BEFORE INSERT OR UPDATE OF age ON employee
FOR EACH ROW
WHEN (NEW.age > 60)
BEGIN
  inform_supervisor;
END;

Supporting Procedure

sql
CREATE OR REPLACE PROCEDURE inform_supervisor
AS
BEGIN
  DBMS_OUTPUT.PUT_LINE('AGE VIOLATION!');
END;

Example 2: Maintain Derived Column Total_sal

Use triggers to maintain the Total_sal column in the DEPARTMENT table (sum of all salaries in the department).

After INSERT or Department Update

sql
CREATE OR REPLACE TRIGGER update_total_sal_insert_or_update
AFTER INSERT OR UPDATE OF Dno ON employee
FOR EACH ROW
BEGIN
  -- Add salary to new department
  UPDATE department
  SET Total_sal = Total_sal + :NEW.salary
  WHERE Dnumber = :NEW.Dno;

  -- Subtract salary from old department if it's an update
  IF UPDATING THEN
    UPDATE department
    SET Total_sal = Total_sal - :OLD.salary
    WHERE Dnumber = :OLD.Dno AND :OLD.Dno IS NOT NULL;
  END IF;
END;

After DELETE

sql
CREATE OR REPLACE TRIGGER update_total_sal_delete
AFTER DELETE ON employee
FOR EACH ROW
WHEN (:OLD.Dno IS NOT NULL)
BEGIN
  UPDATE department
  SET Total_sal = Total_sal - :OLD.salary
  WHERE Dnumber = :OLD.Dno;
END;

Example 3: Preventing Invalid Insert (Salary Check)

sql
CREATE OR REPLACE TRIGGER check_salary
BEFORE INSERT ON employee
FOR EACH ROW
WHEN (:NEW.salary < 3000)
BEGIN
  RAISE_APPLICATION_ERROR(-20001, 'Salary below minimum threshold');
END;

Viewing and Managing Triggers

View all triggers in your schema:

sql
SELECT trigger_name FROM user_triggers;

View trigger source code:

sql
SELECT text FROM user_source 
WHERE name = 'TRIGGER_NAME' AND type = 'TRIGGER';

Drop a trigger:

sql
DROP TRIGGER trigger_name;

Triggers vs Constraints

FeatureTriggersConstraints
PurposeHandle complex business rulesEnforce simple integrity rules
ExecutionDML events (INSERT, UPDATE, DELETE)Built-in integrity checks
FlexibilityCan contain logic and conditionsSimple, declarative rules
Code visibilityStored separately from tableDefined within the table schema
Accepts logic?Yes (PL/SQL allowed)No (limited to conditions only)
ControlPrecise control (row-level, timing)Always checked automatically

Important Points

  • Triggers are automatically invoked — no explicit call.

  • Triggers cannot accept parameters.

  • Too many triggers can impact performance.

  • Triggers should be used when declarative constraints are not sufficient.

  • Oracle doesn’t allow COMMIT, ROLLBACK, or SAVEPOINT inside triggers.

Summary

  • Triggers automate reactions to data modifications

  • Help enforce business logic and maintain data consistency

  • Must be used cautiously to avoid side effects and performance issues

Made with ❤️ for students, by a fellow learner.