3 Triggers
3 Triggers
What is a Trigger?
A trigger is like an automatic alarm. It runs by itself whenever something happens in the
database, such as when a table is updated, a new row is inserted, or a row is deleted.
Think of it as a program that automatically executes when a specific event occurs in the
database.
1. Triggers are automatic programs that run when specific events happen in the database.
2. BEFORE triggers are used to modify or validate data before changes are made.
3. AFTER triggers are used to log or perform actions after the event occurs.
Types of Triggers
Unit: 4 - PL/SQL control statements and stored procedures Dr. Sulbha Gath Page 1
Example 1: BEFORE Trigger
Task: Automatically capitalize the name of a student before adding it to the table.
Code:
Explanation:
1. BEFORE INSERT ON students: The trigger runs before a new row is inserted into the
students table.
2. :NEW.name: Refers to the value being inserted into the name column.
3. UPPER(:NEW.name): Changes the name to uppercase.
What Happens?
If you insert John into the table, it automatically becomes JOHN.
Code:
Explanation:
1. AFTER INSERT ON students: The trigger runs after a new row is added to the students
table.
2. :NEW.name: Refers to the name of the student just added.
3. DBMS_OUTPUT.PUT_LINE: Prints a message about the new student.
What Happens?
If you add a student John, it prints:
A new student has been added: John
Unit: 4 - PL/SQL control statements and stored procedures Dr. Sulbha Gath Page 2