BEFORE Triggers — Complete Guide
BEFORE Triggers — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 54 of 100
BEFORE Triggers
Basics ✓ → Advanced
Advanced · 2 — Production · ~10 min · MySQL — Stored Procedures & Triggers
What is this?
BEFORE triggers fire before the row change is applied. You can validate, modify NEW values, or abort with SIGNAL — the row never commits if you reject.
Why should you care?
Block negative order totals at DB layer even if a buggy API sends minus value.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
CREATE TRIGGER trg_orders_block_negative
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
IF NEW.total_inr < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'total_inr cannot be negative';
END IF;
END;
What happened?
- On INSERT attempt, trigger checks NEW.total_inr.
- SIGNAL raises error — entire INSERT fails.
- BEFORE timing lets you stop bad data pre-commit.
Practice next
- CREATE BEFORE INSERT trigger.
- INSERT valid order — succeeds.
- INSERT negative total — see SIGNAL error.
- Normalize NEW.order_ref to UPPER in BEFORE INSERT.
- BEFORE UPDATE to cap total_inr at 500000.
Remember
BEFORE runs pre-change. NEW is writable in BEFORE INSERT/UPDATE. SIGNAL aborts the statement.
DataFlow pricing guard
Negative total from bad CSV import blocked at trigger before hitting reports.
Outcome: Finance dashboards never show impossible amounts.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!