PL/SQL Triggers (The Alarm) π¨ΒΆ
Prerequisites: DML Basics, PL/SQL Basics
Mentor's Note: A Trigger is a program that Starts Automatically when a specific event happens (like someone updating a salary). It is like a "Security Alarm": you don't call the alarm; the alarm calls you when someone breaks in! π‘
π The Scenario: The Audit Log πΒΆ
Imagine you are a bank manager. - You don't trust everyone. π΅οΈββοΈ - Goal: Every time a salary is changed, you want to record "Who changed it" and "When". - The Trigger: You set a "Sensor" on the Salary column. As soon as a change happens, the trigger wakes up and writes a note in the Audit Table. β
π» 1. Creating a TriggerΒΆ
A trigger usually follows this timing: BEFORE or AFTER.
CREATE OR REPLACE TRIGGER trg_salary_audit
BEFORE UPDATE ON employees
FOR EACH ROW -- π This makes it a "Row-Level" trigger
BEGIN
-- Record the change
INSERT INTO audit_log (msg)
VALUES ('User ' || USER || ' changed salary of ID ' || :OLD.id);
END;
/
π» 2. The :OLD and :NEW Keywords πΒΆ
These are magic values only available inside triggers: - :OLD: The value before the change. - :NEW: The value after the change.
IF :NEW.salary < :OLD.salary THEN
RAISE_APPLICATION_ERROR(-20001, 'You cannot decrease a salary!');
END IF;
π‘οΈ 3. Statement vs. Row Level (Architect's Note)ΒΆ
- Row-Level (
FOR EACH ROW): Fires once for every single row affected. Use this for auditing or validation. - Statement-Level: Fires once per command, even if 1,000 rows are updated. Use this for general security checks.
- Architect's Warning: Too many triggers will slow down your database "Writes" (Inserts/Updates). Use them only for critical business rules! π’
ποΈ 4. Managing TriggersΒΆ
ALTER TRIGGER trg_salary_audit DISABLE; -- Temporarily stop
ALTER TRIGGER trg_salary_audit ENABLE; -- Start again
DROP TRIGGER trg_salary_audit; -- Delete forever