Skip to main content
Albero Academy

Triggers & Scheduled Events

React automatically to data changes with triggers, and run recurring jobs inside the database with the event scheduler.

Chapter 9MySQL14 min readBeginner friendly
  • #MySQL
  • #Triggers
  • #Events

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:

normalise on the way in
DELIMITER //
CREATE TRIGGER lower_email BEFORE INSERT ON students
FOR EACH ROW
BEGIN
SET NEW.email = LOWER(TRIM(NEW.email)); -- clean every inserted email
END //
DELIMITER ;

An audit-log example

A common use is recording history — write a row to an audit table whenever a package changes:

AFTER UPDATE audit
DELIMITER //
CREATE TRIGGER log_pkg_change AFTER UPDATE ON students
FOR EACH ROW
BEGIN
IF NEW.package <> OLD.package THEN
INSERT 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:

a nightly job
SET GLOBAL event_scheduler = ON;
CREATE EVENT purge_old_logs
ON SCHEDULE EVERY 1 DAY
DO
DELETE 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

  1. 01A trigger runs automatically BEFORE/AFTER an INSERT, UPDATE or DELETE.
  2. 02NEW is the incoming row, OLD is the previous — use them to validate, clean or log.
  3. 03A classic use is writing history to an audit table on changes.
  4. 04The event scheduler runs statements on a schedule — a database-native cron.
  5. 05Triggers run invisibly; keep them small, documented, and side-effect-light.