A trigger is code that runs automatically when a row is inserted, updated or deleted. The event scheduler runs code on a timetable. Both let the database maintain itself — keeping history, enforcing rules, and doing housekeeping without an app in the loop.
Triggers
A trigger fires BEFORE or AFTER an INSERT/UPDATE/DELETE. Inside it, NEW is the incoming row and OLD is the previous one:
DELIMITER //CREATE TRIGGER lower_email BEFORE INSERT ON studentsFOR EACH ROWBEGINSET NEW.email = LOWER(TRIM(NEW.email)); -- clean every inserted emailEND //DELIMITER ;
An audit-log example
A common use is recording history — write a row to an audit table whenever a package changes:
DELIMITER //CREATE TRIGGER log_pkg_change AFTER UPDATE ON studentsFOR EACH ROWBEGINIF NEW.package <> OLD.package THENINSERT INTO package_audit(student_id, old_pkg, new_pkg, changed_at)VALUES (OLD.id, OLD.package, NEW.package, NOW());END IF;END //DELIMITER ;
Scheduled events
The event scheduler runs statements on a schedule — a database-native cron. Enable it, then create an event:
SET GLOBAL event_scheduler = ON;CREATE EVENT purge_old_logsON SCHEDULE EVERY 1 DAYDODELETE FROM package_audit WHERE changed_at < NOW() - INTERVAL 1 YEAR;
Use with care
Practice
Write a BEFORE INSERT trigger that lowercases emails, and an AFTER UPDATE trigger that logs package changes to an audit table. Create a daily event that purges audit rows older than a year, and confirm the scheduler is on.
Key takeaways
- 01A trigger runs automatically BEFORE/AFTER an INSERT, UPDATE or DELETE.
- 02NEW is the incoming row, OLD is the previous — use them to validate, clean or log.
- 03A classic use is writing history to an audit table on changes.
- 04The event scheduler runs statements on a schedule — a database-native cron.
- 05Triggers run invisibly; keep them small, documented, and side-effect-light.
