TExcelTAD
Home › MySQL › MySQL Triggers

MySQL Triggers

A trigger is a stored program that runs automatically when rows in a table are inserted, updated or deleted. Nobody calls it: the database fires it as part of the change. Triggers are used for audit logs, for keeping derived values up to date and for checks that constraints can't express.

sql
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
trigger_body;
  • BEFORE triggers run before the row is written and can change the values being written.
  • AFTER triggers run after the row was written; use them to react, for example by logging.
  • FOR EACH ROW: the body runs once per affected row.

Inside the body, NEW.col is the new value (INSERT and UPDATE) and OLD.col the old value (UPDATE and DELETE).

An audit log with AFTER UPDATE

Record every price change:

mysql · try it yourself
CREATE TABLE price_history (
  product_id INT,
  old_price  DECIMAL(8,2),
  new_price  DECIMAL(8,2)
);

CREATE TRIGGER trg_price_audit
AFTER UPDATE ON products
FOR EACH ROW
INSERT INTO price_history (product_id, old_price, new_price)
SELECT OLD.product_id, OLD.unit_price, NEW.unit_price
FROM DUAL
WHERE OLD.unit_price <> NEW.unit_price;

UPDATE products SET unit_price = 25.90 WHERE product_id = 1;
UPDATE products SET units_in_stock = 99 WHERE product_id = 2;    -- price unchanged
UPDATE products SET unit_price = unit_price + 0.10 WHERE category_id = 5;

SELECT * FROM price_history ORDER BY product_id;
+------------+-----------+-----------+
| product_id | old_price | new_price |
+------------+-----------+-----------+
|          1 |     24.50 |     25.90 |
|         16 |      1.99 |      2.09 |
|         17 |      5.49 |      5.59 |
|         18 |      2.49 |      2.59 |
+------------+-----------+-----------+

The stock-only update didn't create a history row thanks to the WHERE in the trigger. In real systems you'd also record when and who (changed_at DATETIME DEFAULT CURRENT_TIMESTAMP, changed_by VARCHAR(80) DEFAULT (CURRENT_USER())).

A one-statement body needs no BEGIN ... END and no DELIMITER. Longer bodies use both, as in the next examples.

Cleaning data with BEFORE INSERT

A BEFORE trigger can modify NEW before the row is stored. Here e-mail addresses are normalised, and a missing city gets a placeholder:

mysql · try it yourself
DELIMITER //
CREATE TRIGGER trg_customers_clean
BEFORE INSERT ON customers
FOR EACH ROW
BEGIN
    SET NEW.email = LOWER(TRIM(NEW.email));
    IF NEW.city IS NULL OR NEW.city = '' THEN
        SET NEW.city = 'Unknown';
    END IF;
END //
DELIMITER ;

INSERT INTO customers (first_name, last_name, email, city, country, signup_date)
VALUES ('Quinn', 'Adams', '  Quinn.Adams@Example.COM ', NULL, 'Ireland', '2025-06-12');

SELECT first_name, email, city FROM customers WHERE last_name = 'Adams';
+------------+-------------------------+---------+
| first_name | email                   | city    |
+------------+-------------------------+---------+
| Quinn      | quinn.adams@example.com | Unknown |
+------------+-------------------------+---------+

Enforcing a rule with SIGNAL

A trigger can reject a change by raising an error with SIGNAL. The whole statement then fails and nothing is written. "Order lines may not be added to cancelled or delivered orders":

mysql · try it yourself
DELIMITER //
CREATE TRIGGER trg_details_open_orders_only
BEFORE INSERT ON order_details
FOR EACH ROW
BEGIN
    IF (SELECT status FROM orders WHERE order_id = NEW.order_id) IN ('cancelled', 'delivered') THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Order is closed';
    END IF;
END //
DELIMITER ;

INSERT INTO order_details (order_id, product_id, quantity, unit_price) VALUES (21, 1, 1, 24.50);
SELECT COUNT(*) AS lines_on_order_21 FROM order_details WHERE order_id = 21;
INSERT INTO order_details (order_id, product_id, quantity, unit_price) VALUES (8, 1, 1, 24.50);
+-------------------+
| lines_on_order_21 |
+-------------------+
|                 3 |
+-------------------+
ERROR 1644 (45000) at line 14: Order is closed

Keeping stock in sync

Triggers on one table can update another. Reduce stock when an order line is added, and give it back when the line is deleted:

mysql · try it yourself
CREATE TRIGGER trg_stock_out AFTER INSERT ON order_details
FOR EACH ROW
UPDATE products SET units_in_stock = units_in_stock - NEW.quantity WHERE product_id = NEW.product_id;

CREATE TRIGGER trg_stock_back AFTER DELETE ON order_details
FOR EACH ROW
UPDATE products SET units_in_stock = units_in_stock + OLD.quantity WHERE product_id = OLD.product_id;

SELECT units_in_stock AS before_order FROM products WHERE product_id = 13;
INSERT INTO order_details (order_id, product_id, quantity, unit_price) VALUES (21, 13, 10, 2.99);
SELECT units_in_stock AS after_order FROM products WHERE product_id = 13;
DELETE FROM order_details WHERE order_id = 21 AND product_id = 13;
SELECT units_in_stock AS after_cancel FROM products WHERE product_id = 13;
+--------------+
| before_order |
+--------------+
|           90 |
+--------------+
+-------------+
| after_order |
+-------------+
|          80 |
+-------------+
+--------------+
| after_cancel |
+--------------+
|           90 |
+--------------+

Managing triggers

mysql · try it yourself
CREATE TRIGGER trg_example BEFORE UPDATE ON suppliers
FOR EACH ROW SET NEW.name = TRIM(NEW.name);

SELECT TRIGGER_NAME, ACTION_TIMING, EVENT_MANIPULATION, EVENT_OBJECT_TABLE
FROM information_schema.TRIGGERS
WHERE TRIGGER_SCHEMA = 'shop';

DROP TRIGGER trg_example;
+--------------+---------------+--------------------+--------------------+
| TRIGGER_NAME | ACTION_TIMING | EVENT_MANIPULATION | EVENT_OBJECT_TABLE |
+--------------+---------------+--------------------+--------------------+
| trg_example  | BEFORE        | UPDATE             | suppliers          |
+--------------+---------------+--------------------+--------------------+

SHOW TRIGGERS; lists them in the client. To change a trigger, drop and recreate it.

Warning: Triggers are invisible to someone reading the application code: a simple INSERT may silently update three other tables. Keep them small, document them, and avoid long trigger chains. TRUNCATE TABLE does not fire DELETE triggers, and foreign-key cascades don't fire triggers either.

Test yourself

In an UPDATE trigger, how do you read the value a column had before the change?

  1. NEW.col
  2. OLD.col
  3. PREV.col
  4. BEFORE.col

Which trigger timing can modify the values being inserted?

  1. AFTER INSERT
  2. BEFORE INSERT
  3. AFTER DELETE
  4. Any of them

How can a trigger reject the change that fired it?

  1. RETURN FALSE
  2. ROLLBACK
  3. SIGNAL SQLSTATE '45000' ...
  4. DELETE NEW