SQL Topics
Trigger Examples
title: Trigger Examples
In the previous lessons, you learned about:
Trigger Introduction
BEFORE Trigger
AFTER Trigger
INSTEAD OF TriggerUnderstanding trigger syntax is important, but real learning happens when you see practical examples.
In enterprise applications, triggers are commonly used for:
Audit Logging
Data Validation
Inventory Management
Salary Tracking
Security Controls
Automatic CalculationsThis lesson contains multiple real-world trigger examples that demonstrate how triggers are used in production database systems.
Why Study Trigger Examples?
Many developers understand trigger syntax but struggle to apply triggers effectively.
Practical examples help you understand:
When To Use Triggers
How To Design Triggers
How To Avoid Common Mistakes
How Enterprise Systems Use TriggersExample 1: Audit Logging Trigger
One of the most common trigger use cases.
Requirement:
Whenever Employee Data Changes
Store Audit InformationCreate Employee Table
CREATE TABLE Employees
(
EmployeeID INT,
EmployeeName VARCHAR(100),
Salary DECIMAL(10,2)
);Create Audit Table
CREATE TABLE EmployeeAudit
(
AuditID INT AUTO_INCREMENT,
EmployeeID INT,
ActionType VARCHAR(20),
ActionDate DATETIME
);AFTER UPDATE Trigger
CREATE TRIGGER EmployeeUpdateAudit
AFTER UPDATE
ON Employees
FOR EACH ROW
BEGIN
INSERT INTO EmployeeAudit
(
EmployeeID,
ActionType,
ActionDate
)
VALUES
(
NEW.EmployeeID,
'UPDATE',
NOW()
);
END;Result
Whenever:
UPDATE Employees
SET Salary = 60000
WHERE EmployeeID = 1;executes:
Audit Record Created AutomaticallyExample 2: Salary Change History
Requirement:
Track Old Salary
Track New Salary
Store Change DateCreate History Table
CREATE TABLE SalaryHistory
(
EmployeeID INT,
OldSalary DECIMAL(10,2),
NewSalary DECIMAL(10,2),
ChangeDate DATETIME
);AFTER UPDATE Trigger
CREATE TRIGGER SalaryTracker
AFTER UPDATE
ON Employees
FOR EACH ROW
BEGIN
INSERT INTO SalaryHistory
VALUES
(
NEW.EmployeeID,
OLD.Salary,
NEW.Salary,
NOW()
);
END;Result
Old and new salary values are preserved automatically.
Example 3: Prevent Negative Salary
Requirement:
Salary Cannot Be NegativeBEFORE INSERT Trigger
CREATE TRIGGER ValidateSalary
BEFORE INSERT
ON Employees
FOR EACH ROW
BEGIN
IF NEW.Salary < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT =
'Salary Cannot Be Negative';
END IF;
END;Result
Invalid salary insertions are blocked.
Example 4: Prevent Salary Reduction
Requirement:
Employee Salary
Cannot DecreaseBEFORE UPDATE Trigger
CREATE TRIGGER PreventSalaryReduction
BEFORE UPDATE
ON Employees
FOR EACH ROW
BEGIN
IF NEW.Salary < OLD.Salary THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT =
'Salary Reduction Not Allowed';
END IF;
END;Result
Salary reductions are rejected.
Example 5: Inventory Management
Requirement:
Reduce Inventory
When Order CreatedProducts Table
CREATE TABLE Products
(
ProductID INT,
ProductName VARCHAR(100),
Quantity INT
);Orders Table
CREATE TABLE Orders
(
OrderID INT,
ProductID INT,
Quantity INT
);AFTER INSERT Trigger
CREATE TRIGGER UpdateInventory
AFTER INSERT
ON Orders
FOR EACH ROW
BEGIN
UPDATE Products
SET Quantity =
Quantity - NEW.Quantity
WHERE ProductID =
NEW.ProductID;
END;Result
Inventory updates automatically.
Example 6: Prevent Product Deletion
Requirement:
Products With Orders
Cannot Be DeletedBEFORE DELETE Trigger
CREATE TRIGGER PreventProductDelete
BEFORE DELETE
ON Products
FOR EACH ROW
BEGIN
IF EXISTS
(
SELECT *
FROM Orders
WHERE ProductID =
OLD.ProductID
)
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT =
'Product Has Orders';
END IF;
END;Result
Deletion prevented.
Example 7: Banking Transaction Log
Requirement:
Track Every Balance ChangeAccounts Table
CREATE TABLE Accounts
(
AccountID INT,
Balance DECIMAL(10,2)
);Transaction Log Table
CREATE TABLE TransactionLog
(
AccountID INT,
OldBalance DECIMAL(10,2),
NewBalance DECIMAL(10,2),
TransactionDate DATETIME
);AFTER UPDATE Trigger
CREATE TRIGGER BalanceAudit
AFTER UPDATE
ON Accounts
FOR EACH ROW
BEGIN
INSERT INTO TransactionLog
VALUES
(
NEW.AccountID,
OLD.Balance,
NEW.Balance,
NOW()
);
END;Result
Every balance change is logged.
Example 8: Automatic Timestamp Update
Requirement:
Update Modified Date
AutomaticallyEmployees Table
CREATE TABLE Employees
(
EmployeeID INT,
EmployeeName VARCHAR(100),
ModifiedDate DATETIME
);BEFORE UPDATE Trigger
CREATE TRIGGER UpdateTimestamp
BEFORE UPDATE
ON Employees
FOR EACH ROW
BEGIN
SET NEW.ModifiedDate =
NOW();
END;Result
Modification date updates automatically.
Example 9: Soft Delete Implementation
Requirement:
Do Not Delete Records
Mark Them As DeletedTable
CREATE TABLE Employees
(
EmployeeID INT,
EmployeeName VARCHAR(100),
IsDeleted BOOLEAN
);INSTEAD OF DELETE Trigger
(SQL Server)
CREATE TRIGGER SoftDelete
ON Employees
INSTEAD OF DELETE
AS
BEGIN
UPDATE Employees
SET IsDeleted = 1
WHERE EmployeeID IN
(
SELECT EmployeeID
FROM DELETED
);
END;Result
Records remain in database.
Only marked as deleted.
Example 10: Student Age Validation
Requirement:
Student Must Be At Least 18
Years OldBEFORE INSERT Trigger
CREATE TRIGGER ValidateAge
BEFORE INSERT
ON Students
FOR EACH ROW
BEGIN
IF NEW.Age < 18 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT =
'Minimum Age Is 18';
END IF;
END;Result
Underage students cannot be inserted.
Example 11: Order Audit System
Requirement:
Track Every New OrderAFTER INSERT Trigger
CREATE TRIGGER OrderAudit
AFTER INSERT
ON Orders
FOR EACH ROW
BEGIN
INSERT INTO OrderHistory
VALUES
(
NEW.OrderID,
NOW()
);
END;Result
Order history maintained automatically.
Example 12: Restrict Weekend Transactions
Requirement:
No Transactions On SundayBEFORE INSERT Trigger
CREATE TRIGGER WeekendRestriction
BEFORE INSERT
ON Transactions
FOR EACH ROW
BEGIN
IF DAYOFWEEK(NOW()) = 1 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT =
'Transactions Disabled';
END IF;
END;Result
Sunday transactions blocked.
Real-World Trigger Use Cases
Banking
Balance Tracking
Transaction Logs
Fraud MonitoringE-Commerce
Inventory Updates
Order Audits
Sales AnalyticsHospital Systems
Patient Record Audits
Prescription Tracking
Appointment LogsPayroll Systems
Salary History
Tax Audits
Bonus TrackingUniversity Systems
Student Registration Logs
Attendance Tracking
Course Enrollment AuditsCommon Trigger Design Patterns
Audit Pattern
Track ChangesValidation Pattern
Block Invalid DataAutomation Pattern
Automatic UpdatesSecurity Pattern
Prevent Unauthorized ActionsSynchronization Pattern
Keep Tables ConsistentBest Practices
Keep Triggers Small
One responsibility per trigger.
Avoid Heavy Logic
Complex processing hurts performance.
Document Trigger Purpose
Improve maintainability.
Test Thoroughly
Validate all scenarios.
Monitor Performance
Check impact on transactions.
Common Interview Questions
What are the most common trigger use cases?
Audit logging, validation, automation, and security.
Can triggers update other tables?
Yes.
Triggers can perform operations on multiple tables.
Are triggers useful for auditing?
Absolutely.
Audit logging is one of the most common trigger applications.
Can triggers prevent invalid data?
Yes.
BEFORE triggers are frequently used for validation.
Which trigger type is best for audit logging?
AFTER Trigger.
Summary
Triggers are powerful automation tools used throughout enterprise database systems. They help enforce business rules, maintain audit trails, automate updates, and ensure data integrity.
In this lesson, you learned:
- Audit Logging Triggers
- Salary Tracking Triggers
- Validation Triggers
- Inventory Management Triggers
- Banking Triggers
- Soft Delete Triggers
- Timestamp Triggers
- Security Triggers
- Real-world use cases
- Best practices
Mastering trigger examples is important because real-world database development relies heavily on practical trigger implementations rather than theoretical concepts alone.
Next Step
Continue to the next module:
Common Table Expressions (CTE) →
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Trigger Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, triggers, trigger
Related SQL Topics