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.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp