MySQL Triggers

December 30, 2021

Table of Contents

What are Triggers in MySQL?

Triggers are routines associated to database tables. These routines are then invoked when a record is added, updated or deleted to those tables.

With Triggers you can perform any sql operation on any table of your database. This is useful, for instance, when you have redundant fields such as accumulators or counters that you want to be updated automatically by the database, instead of having to code it in your application.

Create a Trigger

A Trigger is created with the CREATE TRIGGER instruction as shown in the following code:

delimiter //

create trigger upd_prod_status before update on products
for each row
    if new.quantity <= 0 then
        set new.status = 'out-of-stock';
    elseif new.quantity <= 5 then
        set new.status = 'low-stock';
    elseif new.quantity > 5 then
        set new.status = 'in-stock';
    end if;
end //

delimiter ;

We specify if the trigger will be invoked AFTER or BEFORE the sql instruction, which can be an INSERT, UPDATE, or DELETE.

Inside the BEGIN and END statements, we will put our code.

Trigger Invocation

With the Trigger created in the code shown above, once we perform a sql update operation such as:

update `products` set `quantity` = '95' where `products`.`id` = 1; 

We will see the additional change done on the table:

// When querying the table we will find the `status` field was also automatically modified
select id, status from `products` where id = 1;

id status
1 in-stock

Additional Example

In the example shown above we have updated a field from the same table where the trigger was defined.

In the next example below, we are affecting other tables, to illustrate that the triggers are not restricted to their associated table, but that indeed can perform any sql operation in other tables of the database.

delimiter //

create trigger upd_prod_tables after insert on products
for each row
    insert into product_tags (product_id, tag) values (, 'new-product');
    update product_categories set num_products = num_products + 1 where category_id = new.category_id;
end //

delimiter ;

Drop a Trigger

When you no longer need a Trigger you can delete it with the DROP TRIGGER instruction.

drop trigger upd_prod_status;

drop trigger upd_prod_tables;