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.
💻 Live Code Editor
Is page ki language (MYSQL) mein code likhein aur turant chalाएं — yahीं, bina kuch install kiye.Powered by OneCompiler. Agar editor na khule to yahान naye tab mein kholein.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.