mysql
  1. mysql-how-to-use-mysqlafter-trigger

How to Use MySQL After Trigger

MySQL triggers are stored programs that are executed automatically in response to certain events. Triggers can be used to enforce business rules, log changes to a table, or perform calculations before or after an operation.

In this tutorial, we'll focus on how to use an after trigger in MySQL.

Syntax

The basic syntax for creating an after trigger in MySQL is as follows:

CREATE TRIGGER trigger_name
AFTER insert/update/delete ON table_name
FOR EACH ROW
BEGIN
   -- Trigger code here
END;

Let's break down this syntax:

  • First, we use the CREATE TRIGGER statement to create a new trigger.
  • After the trigger name, we specify the trigger event using the AFTER keyword followed by the event (insert, update, or delete).
  • Next, we specify the name of the table that the trigger will be associated with using the ON keyword.
  • The FOR EACH ROW clause tells MySQL to execute the trigger once for each row affected by the event.
  • Finally, the trigger code is enclosed within a BEGIN and END block.

Example

Let's say we have a table called orders with the following columns:

  • id (int)
  • product (varchar)
  • quantity (int)
  • price (decimal)

We want to create an after trigger that calculates the total cost of each order and updates a column called total_cost. Here's what the trigger would look like:

CREATE TRIGGER calc_total_cost
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
   UPDATE orders SET total_cost = quantity * price WHERE id = NEW.id;
END;

In this trigger, we're using the NEW keyword to refer to the row being inserted. The UPDATE statement then calculates the total cost by multiplying the quantity and price columns and updates the total_cost column with the result.

Explanation

In the above example, we have created an after trigger named calc_total_cost on the orders table that is executed after each insert.

For each newly inserted row, the trigger code updates the corresponding total_cost column by multiplying the quantity and price columns.

Use

After triggers in MySQL can be used to automate various tasks such as logging changes to a table, enforcing business rules, or performing calculations before or after an operation.

Important Points

  • The trigger event can be an insert, update, or delete operation.
  • The code within a trigger must be enclosed within a BEGIN and END block.
  • The OLD and NEW keywords can be used to refer to the old and new rows being updated, respectively.

Summary

In this tutorial, we explained how to create an after trigger in MySQL. We covered the basic syntax, provided an example, explained the output, and covered some important points. With this knowledge, you can use after triggers to perform automated tasks or enforce business rules in your MySQL database.

Published on: