⥠A Trigger is a special database object thatautomatically executes (fires) in response to specific database events, such as INSERT, UPDATE, orDELETE operations on a table or view. Triggers help enforce business rules, maintain data integrity, automate auditing, and synchronize related data without requiring application code.
đ What is a Trigger?
Unlike stored procedures or functions, a trigger is not executed manually. Instead, the database automatically runs it whenever the associated event occurs. Triggers execute as part of the transaction that caused them to fire.
Information
đ¯ Why Use Triggers?
Triggers automate tasks that should always occur whenever certain database events happen.
- đ Automatically enforce business rules.
- đ Maintain data consistency.
- đ Record audit logs.
- đ Validate data before or after modifications.
- đ Synchronize related tables.
- đ Reduce repetitive application logic.
đ Sample Table
| StudentID | Name | Department |
|---|---|---|
| 101 | Alice | Computer Science |
| 102 | Bob | Mathematics |
| 103 | Charlie | Physics |
đ Basic Trigger Syntax
The exact syntax differs across database systems. The following example uses a generic SQL structure.
Generic Trigger Syntax
CREATE TRIGGER trigger_name
AFTER INSERT
ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic
END;đ Types of Triggers
| Trigger Type | Description |
|---|---|
| BEFORE Trigger | Executes before the triggering operation. |
| AFTER Trigger | Executes after the triggering operation completes. |
| INSTEAD OF Trigger | Executes instead of the triggering operation (supported by some databases). |
đĄ Example: AFTER INSERT Trigger
Suppose you want to record every newly added student in an audit table.
Audit Trigger
CREATE TRIGGER trg_AfterInsertStudent
AFTER INSERT
ON Students
FOR EACH ROW
BEGIN
INSERT INTO StudentAudit
(StudentID, Action)
VALUES
(NEW.StudentID, 'Inserted');
END;Important
â Trigger Execution Example
Insert a Student
INSERT INTO Students
(StudentID, Name, Department)
VALUES
(104, 'David', 'Physics');When this statement executes successfully, the trigger automatically inserts a corresponding record into the audit table.
đĄ Example: BEFORE UPDATE Trigger
A trigger can validate or modify data before it is updated.
BEFORE UPDATE Trigger
CREATE TRIGGER trg_BeforeUpdateStudent
BEFORE UPDATE
ON Students
FOR EACH ROW
BEGIN
-- Validation or business logic
END;đĄ Example: AFTER DELETE Trigger
Triggers are often used to log deleted records.
Delete Audit Trigger
CREATE TRIGGER trg_AfterDeleteStudent
AFTER DELETE
ON Students
FOR EACH ROW
BEGIN
INSERT INTO StudentAudit
(StudentID, Action)
VALUES
(OLD.StudentID, 'Deleted');
END;đ Trigger Workflow
| Step | Description |
|---|---|
| Event Occurs | An INSERT, UPDATE, or DELETE statement executes. |
| Trigger Fires | The associated trigger runs automatically. |
| Logic Executes | The trigger performs its defined actions. |
| Transaction Continues | The database completes or rolls back the transaction based on the outcome. |
âī¸ Triggers vs Stored Procedures
| Feature | Trigger | Stored Procedure |
|---|---|---|
| Execution | Automatic | Manual |
| Triggered By | Database events | User or application call |
| Accept Parameters | â No | â Yes |
| Main Purpose | Automate event-driven actions. | Perform reusable database operations. |
đŧ Real-World Example
A banking system automatically records every balance update in an audit table. Whenever an account balance changes, a trigger captures the old value, new value, timestamp, and user information to maintain a complete transaction history.
Conceptual Audit Trigger
CREATE TRIGGER trg_AuditBalance
AFTER UPDATE
ON Accounts
FOR EACH ROW
BEGIN
-- Record old and new balances
END;đī¸ Database Compatibility
| Database System | Trigger Support |
|---|---|
| MySQL | â Supports BEFORE and AFTER triggers. |
| PostgreSQL | â Supports row-level and statement-level triggers. |
| SQL Server | â Supports AFTER and INSTEAD OF triggers. |
| Oracle | â Extensive trigger support using PL/SQL. |
| SQLite | â Supports BEFORE, AFTER, and INSTEAD OF triggers. |
â ī¸ Advantages
- â Automatically enforce business rules.
- â Maintain consistent data.
- â Automate auditing.
- â Reduce repetitive application code.
- â Help maintain referential integrity in specialized scenarios.
â ī¸ Limitations
- â Can make database behavior harder to understand.
- â May affect performance if trigger logic is expensive.
- â Complex trigger chains can be difficult to debug.
- â Syntax and capabilities differ across database systems.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ Triggers execute automatically when specific database events occur.
- đ They commonly respond to INSERT, UPDATE, and DELETE operations.
- đ Triggers are useful for auditing, validation, and enforcing business rules.
- đ They differ from stored procedures because they are event-driven.
- đ Trigger syntax and features vary among database systems.
- đ Use triggers carefully to balance automation, maintainability, and performance.