- Advanced SQL
-
Overview
- Indexing for Performance Optimization
- Transactions and ACID Properties
- Triggers and Event Scheduling in SQL
- Window Functions and Ranking
- Pivoting Data in SQL
- JSON and XML Data Handling
- Recursive Queries in SQL
- Performance Tuning and Query Optimization
- Role-Based Access Control in Databases
- Handling Large Datasets in SQL
Triggers and Event Scheduling in SQL
Add to BookmarkIntroduction
Triggers and event scheduling in SQL help automate database tasks. Triggers automatically execute in response to specific changes in a table, while events run at scheduled times. These features improve data consistency and automate routine tasks like logging, notifications, and cleanup operations.
What are SQL Triggers?
A trigger is a special type of stored procedure that runs automatically when a specified event occurs in a table. It is commonly used for:
- Enforcing business rules (e.g., preventing negative bank balances)
- Auditing changes (e.g., logging updates or deletions)
- Maintaining data integrity (e.g., synchronizing data between tables)
Types of Triggers in SQL
Triggers can be classified based on when they execute and what they act on:
| Type | Description |
|---|---|
| BEFORE Trigger | Executes before an INSERT, UPDATE, or DELETE operation. |
| AFTER Trigger | Executes after the specified operation is completed. |
| INSTEAD OF Trigger | Replaces the default operation with custom logic (used in views). |
| ROW-Level Trigger | Executes once for each row affected by the operation. |
| STATEMENT-Level Trigger | Executes once per statement, regardless of the number of rows affected. |
Example: Creating a Trigger
A trigger that logs changes in an employees table:
CREATE TABLE employee_log (
log_id INT AUTO_INCREMENT PRIMARY KEY,
emp_id INT,
action_type VARCHAR(10),
action_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TRIGGER after_employee_update
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO employee_log (emp_id, action_type)
VALUES (OLD.id, 'UPDATE');Whenever an UPDATE occurs in the employees table, the change is logged in employee_log.
Example: Preventing Negative Balance in a Bank System
CREATE TRIGGER prevent_negative_balance
BEFORE UPDATE ON accounts
FOR EACH ROW
BEGIN
IF NEW.balance < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Balance cannot be negative';
END IF;
END;If an update tries to set a negative balance, the trigger prevents it.
What is Event Scheduling in SQL?
Events are automated tasks that run at scheduled times in MySQL or PostgreSQL. They are useful for:
- Data cleanup (e.g., deleting old records)
- Sending notifications (e.g., reminders for subscriptions)
- Automating backups
Enabling the Event Scheduler
To use events in MySQL, first enable the scheduler:
SET GLOBAL event_scheduler = ON;Creating a Scheduled Event
An event that deletes inactive users every day:
CREATE EVENT delete_inactive_users
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM users WHERE last_login < NOW() - INTERVAL 90 DAY;This event runs daily and removes users who haven't logged in for 90 days.
Example: Automating a Monthly Report
CREATE EVENT generate_monthly_report
ON SCHEDULE EVERY 1 MONTH
DO
INSERT INTO reports (report_date, total_sales)
SELECT CURDATE(), SUM(amount) FROM sales;This event calculates the total sales every month and stores it in a reports table.
Managing Events
- List all events:
SHOW EVENTS; - Disable an event:
ALTER EVENT delete_inactive_users DISABLE;- Drop an event:
DROP EVENT delete_inactive_users;Triggers vs. Events: Key Differences
| Feature | Triggers | Events |
|---|---|---|
| Execution | Runs immediately after a table operation | Runs at a scheduled time |
| Use Cases | Data validation, logging, automation | Cleanup, reports, scheduled tasks |
| Scope | Table-level | Database-wide |
| Control | Cannot be disabled | Can be enabled/disabled |
Conclusion
Triggers and event scheduling are powerful tools for automating database management. Triggers help enforce rules and maintain data integrity, while events handle scheduled tasks. Properly using these features can improve efficiency and reduce manual work.
Prepare for Interview
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
Random Blogs
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Understanding SQL vs MySQL vs PostgreSQL vs MS SQL vs Oracle and Other Popular Databases
- Exploratory Data Analysis On Iris Dataset
- Datasets for analyze in Tableau
- Extract RGB Color From a Image Using CV2
- Data Analytics: The Power of Data-Driven Decision Making
- Python Challenging Programming Exercises Part 2
- Deep Learning (DL): The Core of Modern AI
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- What Is SEO and Why Is It Important?
- What to Do When Your MySQL Table Grows Too Wide
- String Operations in Python
- Generative AI - The Future of Artificial Intelligence
- Python Challenging Programming Exercises Part 1
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset

