MySQL + SQL · Lesson 98
Triggers in MySQL
What is a Trigger?
A trigger is SQL that runs AUTOMATICALLY when an INSERT, UPDATE or DELETE happens on a table. You never call it directly — the event fires it.
Example: Auto Log
DELIMITER //
CREATE TRIGGER after_student_insert
AFTER INSERT ON students
FOR EACH ROW
BEGIN
INSERT INTO logs(message)
VALUES(CONCAT('New student: ', NEW.name));
END //
DELIMITER ;Every time a student is added, a log row is created automatically.
NEW and OLD
NEW.column= the new value (INSERT/UPDATE).OLD.column= the old value (UPDATE/DELETE).
Summary
- A trigger runs automatically on INSERT/UPDATE/DELETE.
- Use NEW/OLD to access changed values; great for logging and validation.