</>
Skip to content
MySQL lessons (43/48)

MySQL — Triggers

Basic Trigger

DELIMITER //
CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
    SET NEW.created_at = NOW();
END //
DELIMITER ;

Trigger Events

EventFires When
BEFORE INSERTBefore a row is inserted
AFTER INSERTAfter a row is inserted
BEFORE UPDATEBefore a row is updated
AFTER UPDATEAfter a row is updated
BEFORE DELETEBefore a row is deleted
AFTER DELETEAfter a row is deleted

Audit Log Trigger

CREATE TABLE audit_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    action VARCHAR(20),
    table_name VARCHAR(50),
    record_id INT,
    changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DELIMITER //
CREATE TRIGGER audit_users_update
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
    INSERT INTO audit_log (action, table_name, record_id)
    VALUES ('UPDATE', 'users', OLD.id);
END //
DELIMITER ;

NEW and OLD Keywords

-- OLD = the existing row value
-- NEW = the new value being set

DELIMITER //
CREATE TRIGGER prevent_negative_salary
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
    IF NEW.salary < 0 THEN
        SET NEW.salary = OLD.salary;
    END IF;
END //
DELIMITER ;

Viewing Triggers

SHOW TRIGGERS;
SHOW TRIGGERS LIKE 'users%';

Dropping Triggers

DROP TRIGGER IF EXISTS before_insert_users;

Mini Practice

Write SQL code that:

  1. Creates a BEFORE INSERT trigger
  2. Creates an AFTER UPDATE trigger for auditing
  3. Uses OLD and NEW keywords
  4. Views and drops a trigger

Up Next

Continue with Events — MySQL's built-in task scheduler.

Related Topics

Frequently Asked Questions about Triggers

What is Triggers in MySQL?

Triggers is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Triggers?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Triggers.

Why is Triggers important in MySQL?

Triggers is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.