DBMS Exp 9
DBMS Exp 9
9
AIM: Implement different types of triggers.
THEORY:
Triggers in PL/SQL
1. Definition of Triggers: A trigger is a special type of stored procedure in PL/SQL that
automatically executes in response to specific events on a table or view. Triggers are used to
enforce business rules, maintain data integrity, and automate system tasks without requiring
explicit calls from applications.
2. Syntax for Writing a Trigger in PL/SQL:
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF}
{INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
[WHEN (condition)]
DECLARE
-- Variable declarations (optional)
BEGIN
-- Trigger body (PL/SQL statements)
-- Actions to be performed when the trigger is fired
END;
3. Types of Triggers: Triggers can be categorized based on the type of operation they
respond to:
Insert Triggers:
o These triggers are executed automatically after a new row is inserted into a
table.
o They can be used to validate or modify data before it's committed to the
database.
Example Use Cases:
o Automatically populating audit fields (e.g., timestamps, user information).
o Enforcing referential integrity between tables.
Delete Triggers:
o These triggers are executed before or after a row is deleted from a table.
o They can be used to enforce constraints or maintain historical records.
Example Use Cases:
o Preventing deletion if certain conditions are met (e.g., if the row is referenced
in another table).
o Archiving deleted data into another table for record-keeping.
Update Triggers:
o These triggers are executed before or after a row is updated in a table.
o They can be used to validate new values or track changes over time.
Example Use Cases:
o Automatically logging changes for auditing purposes.
o Enforcing business rules (e.g., preventing updates to certain columns).
4. Timing of Triggers: Triggers can also be classified based on when they execute in relation
to the triggering event:
Before Triggers:
o Executed before the triggering event (insert, update, or delete).
o Useful for validating or modifying input data before it is applied to the
database.
Example Use Cases:
o Validating data for integrity (e.g., checking for null values).
o Modifying data before it's inserted or updated (e.g., setting default values).
After Triggers:
o Executed after the triggering event has completed.
o Useful for performing actions that depend on the completion of the event.
Example Use Cases:
o Sending notifications or alerts after a record is modified.
o Updating related tables or performing calculations based on changes made.
Trigger for Notification of High Damage Claims