SyntaxStudy
Sign Up
MySQL BEFORE INSERT and AFTER INSERT Triggers
MySQL Intermediate 7 min read

BEFORE INSERT and AFTER INSERT Triggers

INSERT triggers fire when a new row is added to a table. BEFORE INSERT triggers allow you to modify or validate the incoming data before it is saved. AFTER INSERT triggers are used to take action based on the newly inserted row.

BEFORE INSERT Use Cases

  • Automatically set a default value based on other columns
  • Validate that required fields meet business rules
  • Format data (e.g., uppercase a code field)

AFTER INSERT Use Cases

  • Log the insertion to an audit table
  • Update a summary or counter table
  • Send a notification (via an application hook)

In a BEFORE INSERT trigger, you can modify NEW.column_name to change the value that gets stored. In an AFTER INSERT trigger, NEW is read-only and reflects what was actually stored.

Example
DELIMITER //

-- BEFORE INSERT: auto-set slug from title
CREATE TRIGGER before_article_insert
BEFORE INSERT ON articles
FOR EACH ROW
BEGIN
    SET NEW.slug = LOWER(REPLACE(NEW.title, ' ', '-'));
    SET NEW.created_at = NOW();
END //

-- AFTER INSERT: log to audit table
CREATE TRIGGER after_article_insert
AFTER INSERT ON articles
FOR EACH ROW
BEGIN
    INSERT INTO audit_log (table_name, action, record_id, changed_at)
    VALUES ('articles', 'INSERT', NEW.id, NOW());
END //

DELIMITER ;
Pro Tip

Keep trigger logic lightweight to avoid slowing down every INSERT operation.