A Comprehensive Guide To MySQL Triggers [6 Examples Inside!]

Try this guide with our instant dedicated server for as low as 40 Euros

MySQL Triggers

By providing your email address or using a single sign-on provider to create an account, you agree to our Terms of Service and that you have reviewed our Privacy Policy.

Thank you for contacting us! We will get in touch with you soon.

MySQL triggers are powerful database objects that automatically execute in response to specific events occurring in a MySQL database. 

These events can include INSERT statements, UPDATE, or DELETE operations on tables within the database. Triggers enable developers to enforce data integrity, automate tasks, and implement complex business logic directly within the database.

As you can imagine, mastering MySQL triggers can significantly improve your ability to manage databases and optimize the operation of your applications. 

In this comprehensive guide, we will explore the fundamentals of MySQL triggers, including their syntax, types, and practical use cases.

However, before understanding the steps in creating, updating, and deleting a trigger, let us understand what is a trigger in MySQL, its types, and its features. 

Table Of Contents

  1. What is a Trigger in MySQL
    1. Types of Triggers
    2. Key Characteristics of Triggers
  2. Trigger Syntax and Database Setup
    1. Creating Triggers
    2. Deleting Triggers
    3. Create a Test Table (Optional)
  3. MySQL Triggers With Examples
    1. The Prerequisites:
    2. Trigger #1: BEFORE INSERT
    3. Trigger #2: AFTER INSERT
    4. Trigger #3: BEFORE UPDATE
    5. Trigger #4: AFTER UPDATE
    6. Trigger #5: BEFORE DELETE
    7. Trigger #6: AFTER DELETE
  4. Conclusion
  5. FAQs

What is a Trigger in MySQL

A trigger is a database object that automatically executes when specific events occur on a table or view. Common events in this case can include INSERT, UPDATE, and DELETE. 

Within a database, triggers carry out a variety of automated functions, including maintaining business rules, verifying data, keeping audit trails, and automatically updating relevant tables. 

As a result, developers and database administrators can use triggers as a seamless mechanism for preserving the consistency and integrity of data within databases.

Types of Triggers

Triggers are classified into two main types of triggers, based on timing of execution. 

The BEFORE Triggers

The triggers are executed before the triggering event (e.g., BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE). 

You can use these triggers to read and modify the data being inserted/updated. Typically, they are used for validating or modifying data before it is committed to the database.

The AFTER Triggers

These triggers are executed after the triggering event (e.g., AFTER INSERT, AFTER UPDATE, AFTER DELETE). 

In most cases, they can only read the data after the event has occurred. As such, you can use these triggers for actions that require the assurance that the triggering event has been completed successfully. Typical applications include logging, auditing, or updating other tables based on the changes.

There are six trigger combinations in MySQL, all depending on the activation time and the event. While the AFTER triggers execute statements after the event, the BEFORE triggers validate the data and make adjustments before committing. These triggers automatically impact all newly added, removed, or updated rows referenced within the statement.

Key Characteristics of Triggers

Some of the key characteristics of MySQL triggers are:

  • Event-Driven Execution: Triggers are automatically invoked by certain events on a table, like INSERT, UPDATE, or DELETE actions.
  • Bound to a Table: Each trigger is associated with a specific table and is triggered by actions on that table.
  • Timing: Triggers can be programmed to execute before or after the triggering event. For instance, a trigger on a table can execute AFTER UPDATE or BEFORE INSERT.
  • Automatic Invocation: The MySQL database engine automatically invokes triggers. There is no need to add direct calls to user applications.

Trigger Syntax and Database Setup

After that brief introduction, let’s discuss the syntax of the MySQL triggers. We will discuss the syntax for creating and deleting triggers.

Creating Triggers

To create a new trigger, use the CREATE TRIGGER statement syntax:

mysql> CREATE TRIGGER <trigger name> <trigger time > <trigger event>
              ON <table name>
              FOR EACH ROW
              <trigger body>;

Here,

 <trigger_name>: A unique identifier you choose for the trigger 

<trigger_timing>: Specifies when the trigger fires – either BEFORE or AFTER.

<trigger_event>: The specific database event that triggers the action – INSERT, UPDATE, or DELETE.

<table_name>: The table on which the trigger is defined.

FOR EACH ROW: Indicates the trigger executes for each affected row during the event.

Deleting Triggers

There are two ways to remove a trigger from your MySQL database:

  1. DROP TRIGGER 
  2. DROP TRIGGER IF EXISTS.

The DROP TRIGGER statement is the basic statement to remove a trigger. The syntax is as follows:

mysql> DROP TRIGGER <trigger name>;

DROP TRIGGER

Replace <trigger_name> with the actual name of the trigger you want to delete.

The alternative DROP TRIGGER IF EXISTS command is safer as it avoids errors if the trigger you’re trying to delete doesn’t exist. The syntax is:

mysql> DROP TRIGGER IF EXISTS <trigger name>;

This statement deletes the trigger but won’t raise an error if it’s not found.

Create a Test Table (Optional)

We strongly recommend creating a test table to practice the triggers we will mention later on in this tutorial. 

Start by running the following statement to create a sample table:

mysql> CREATE TABLE student (name varchar(45), age int);

CREATE TABLE student

Next, insert sample data into the table:

mysql> INSERT INTO student (name, age) VALUES ('Alice', '19');

INSERT INTO student

Finally, run the following SELECT table to see the results:

mysql> SELECT * FROM student;

SELECT FROM student

MySQL Triggers With Examples

Let’s see the six MySQL triggers in detail. 

The Prerequisites:

Before diving in, ensure you have the following,

  • A MySQL database
  • Basic MySQL knowledge
  • A user account with administrative privileges

Trigger #1: BEFORE INSERT

The BEFORE INSERT trigger allows for control over data modification before it is committed into a database table. This can be useful for enforcing data validation rules, data manipulation, or error handling.

The BEFORE INSERT syntax is:

mysql> DELIMITER //

mysql> CREATE TRIGGER before_insert_trigger

              BEFORE INSERT ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

              END;

              //

             DELIMITER ;

This trigger code executes before a new row is inserted into the specified table (table_name)

BEFORE INSERT Trigger Example

Consider the following example: 

mysql> DELIMITER //

mysql> CREATE TRIGGER before_insert_student

              BEFORE INSERT ON student

              FOR EACH ROW

              BEGIN

              -- Check if the student's age is greater than or equal to 18

              IF NEW.age < 18 THEN

              SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Student must be at least  18 years old';

              END IF;

              -- Additional trigger logic here if needed

              END;

              //

              DELIMITER ;

BEFORE INSERT Trigger Example

student must bhe 18 years

 Here,

  • The trigger is named before_insert_student and is created to execute before an insertion operation (BEFORE INSERT) on the student table.
  • FOR EACH ROW specifies that the trigger should be executed for each inserted row.

In this example, the trigger checks if the student’s age being inserted (accessed through NEW.age) is less than 18. If it is, the trigger raises an error using the SIGNAL statement, preventing the insertion.

You can add additional logic inside the trigger body (between BEGIN and END) to check other conditions or modify the inserted data.

Trigger #2: AFTER INSERT

AFTER INSERT triggers fire after a new row is inserted into a table. They’re commonly used for tasks like logging inserts or updating other tables based on the newly inserted data.

These triggers come in handy when the referenced row produces a value required to update another table.

The AFTER INSERT syntax is:

mysql> DELIMITER //

mysql> CREATE TRIGGER after_insert_trigger

              AFTER INSERT ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

              END;

              //

              DELIMITER ;

This trigger works after a new row is inserted into the table (table_name).

The AFTER INSERT Example

Consider the following statement:

mysql> DELIMITER //

mysql> CREATE TRIGGER after_insert_student

              AFTER INSERT ON student

              FOR EACH ROW

              BEGIN

              -- Insert a record into the student_log table to log the insertion

              INSERT INTO student_log (action, timestamp)

              VALUES ('INSERT', NOW());

              END;

              //

             DELIMITER ;

The AFTER INSERT Example

Here,

  • The trigger is named after_insert_student and is created to execute after an insertion operation (AFTER INSERT) on the student table.
  • FOR EACH ROW specifies that the trigger should be executed for each row inserted into the student table.
  • We have the trigger logic inside the trigger’s body (between BEGIN and END).
  • The NEW.student_id refers to the student_id of the newly inserted row.

In this example, When a new row is inserted into the student table, the trigger inserts a corresponding record into the student_log table. This is a common practice for logging purposes, allowing you to track changes made to the student table over time.

The NOW() function returns the current timestamp, which records the insertion time in the student_log table.

Trigger #3: BEFORE UPDATE

BEFORE UPDATE triggers fire before an existing row is updated in a table. These triggers come in handy when the entered row produces a value required to update another table.

The typical syntax is as follows:

mysql> DELIMITER //

mysql> CREATE TRIGGER before_update_trigger

              BEFORE UPDATE ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

              END;

              //

            DELIMITER ;

This trigger fires before an existing row is updated in the table (table_name). It allows you to set up data validation rules, add error handling, or modify data before updating.

A BEFORE UPDATE Example

Consider the following statement:

mysql> DELIMITER //

mysql> CREATE TRIGGER before_update_student

              BEFORE UPDATE ON student

              FOR EACH ROW

              BEGIN

              -- Check if the student's age is being modified to less than 18

              IF NEW.age < 18 THEN

             SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Student must be at least  18 years old';

             END IF;

             END;

             //

            DELIMITER ;

A BEFORE UPDATE Example

Here,

  • The trigger, named before_update_student, is created to execute before an update operation (BEFORE UPDATE) on the student table.
  • FOR EACH ROW indicates that each time a row is updated, the trigger will be executed.
  • In this example, the trigger checks if the student’s age being updated (accessed through NEW.age) is less than 18. If it is, the trigger raises an error using the SIGNAL statement, preventing the update.

You can add additional logic inside the trigger, such as checking other conditions or modifying the updated data.

Trigger #4: AFTER UPDATE

AFTER UPDATE triggers fire after an existing row is updated in a table (table_name). Data commit changes are tracked with the use of the AFTER UPDATE statement. 

mysql> DELIMITER //

mysql> CREATE TRIGGER after_update_trigger

              AFTER UPDATE ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

              END;

              //

              DELIMITER ;

AFTER UPDATE is commonly used for tasks such as logging or updating other tables based on the updated data.

AFTER UPDATE Example

mysql> DELIMITER //

mysql> CREATE TRIGGER after_update_student

              AFTER UPDATE ON student

              FOR EACH ROW

              BEGIN

              -- Update the student_history table to record the changes

              INSERT INTO student_history (action, timestamp)

              VALUES ('UPDATE', NOW());

              END;

              //

              DELIMITER ;

  • This trigger is named after_update_student and is created to execute after an update operation (AFTER UPDATE) on the student table.
  • FOR EACH ROW specifies that the trigger should be executed for each row updated in the student table.
  • We have the trigger logic inside the trigger’s body (between BEGIN and END).
  • The OLD.student_id refers to the student_id of the row before it was updated.
  • The NOW() function returns the current timestamp, which is used to record the time of the update in the student_history table.

In this example, the trigger inserts a corresponding record after a row is updated in the table. This allows you to track changes made to the student table over time.

AFTER UPDATE Example

Trigger #5: BEFORE DELETE 

The BEFORE DELETE trigger is important from a security perspective. This trigger assists in preventing accidental deletion, an important aspect of maintaining data integrity. 

In some cases, you can use this trigger to set up archiving of data items before the data deletion statements are executed. 

The syntax of this trigger is usually as follows:

mysql> DELIMITER //

mysql> CREATE TRIGGER before_delete_trigger

              BEFORE DELETE ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

              END;

             //

            DELIMITER ;

This trigger fires before a row is deleted from the table (table_name). It allows you to perform checks or modify the data before it is deleted.

A BEFORE DELETE Example

mysql> DELIMITER //

mysql> CREATE TRIGGER before_delete_student

              BEFORE DELETE ON student

              FOR EACH ROW

              BEGIN

              -- Check if the student has any associated table records in another table

              IF (SELECT COUNT(*) FROM other_table WHERE student_id = OLD.student_id) > 0 THEN

             SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete student with associated records';

              END IF;

              END;

              //

             DELIMITER ;

A BEFORE DELETE Example

  • This trigger, before_delete_student, is created to execute before a delete operation (BEFORE DELETE) on the student table.
  • The expression on EVERY ROW instructs the trigger to run on every deleted row.
  • We have the trigger logic inside the trigger’s body (between BEGIN and END).

In this example, the trigger checks if the student being deleted (accessed through OLD.student_id) has any associated records in another table (other_table). If there are associated records, the trigger raises an error using the SIGNAL statement, preventing the deletion.

Trigger #6: AFTER DELETE

When a data row is removed before the updates are applied, the AFTER DELETE trigger preserves the information changes.

The typical syntax of this trigger is as follows:

mysql> DELIMITER //

mysql> CREATE TRIGGER after_delete_trigger

              AFTER DELETE ON table_name

              FOR EACH ROW

              BEGIN

              -- Trigger logic here

            END;

            //

           DELIMITER ;

An AFTER DELETE Example

This trigger fires after a row has been deleted from the specified table (table_name). It is commonly used for tasks such as logging or updating other tables based on the relationship with the deleted data.

An AFTER DELETE Example

Consider the following example statements:

mysql> DELIMITER //

mysql> CREATE TRIGGER after_delete_student

              AFTER DELETE ON student

              FOR EACH ROW

              BEGIN

              -- Insert into table student_deleted_log to log the deletion

              INSERT INTO student_deleted_log (action, timestamp)

              VALUES ( 'DELETE', NOW());

              END;

              //

             DELIMITER ;

  • This trigger, named after_delete_student, is created to execute after a delete operation (AFTER DELETE) on the student table.
  • FOR EACH ROW specifies that the trigger should be executed for each row deleted from the student table.
  • We have the trigger logic inside the trigger’s body (between BEGIN and END).
  • The OLD.student_id refers to the student_id of the row before it was deleted.
  • The NOW() function returns the current timestamp, which records the time of the deletion in the student_deleted_log table.

In this example, after a row is deleted from the student table, the trigger inserts a corresponding record into the student_deleted_log table. This allows you to track deletions made to the student table over time.

Conclusion

MySQL triggers offer a robust mechanism for automating database operations and enforcing data integrity. This article provides a detailed explanation of trigger syntax, its functionality, and versatile applications. Understanding the timing parameter further enhances the versatility of triggers, enabling precise control over when trigger actions are executed. With this knowledge, developers can harness the power of MySQL triggers to streamline database management and enhance application functionality effectively.

At RedSwitches, we’re dedicated to helping you discover the perfect server solutions to drive your business to new heights. So, if you’re looking for a robust server, we offer the best-dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. How are errors handled during trigger execution?

Errors during trigger execution can be handled using error handling mechanisms such as the SIGNAL statement to raise custom error conditions or exceptions.

Q. What is a Row-Level Trigger?

A row-level trigger is a type of trigger in a database management system that executes once for each row impacted by a triggering event. It allows more precise control over trigger actions at the specific row level.

Q. What triggers trigger invocation?

The database management system can automatically invoke triggers in response to specific events, such as row-level operations (INSERT, UPDATE, DELETE). These events primarily focus on data manipulation operations that affect the contents of tables.

Q. How do triggers interact with transactional tables?

Triggers can be applied to transactional tables to enforce data consistency and integrity constraints within the transaction’s scope.

Q. What type of operations can triggers respond to?

Triggers can respond to various types of operations, including INSERT, UPDATE, and DELETE statements executed by client applications. They are designed to respond to specific database operations that manipulate data in tables.

Q. What privileges are required for trigger creation?

Users must have the appropriate permissions, including the SUPER privilege, which allows them to create triggers and other database objects. 

Q. How do statement inserts affect trigger execution?

Statement-level triggers are invoked once for each SQL statement executed, making them suitable for handling bulk operations such as statement inserts.

Q. What considerations are important for server setup when using triggers?

It’s essential to consider server performance and resource utilization when using triggers, as triggers can introduce additional overhead, particularly in high-volume environments.

Try this guide with our instant dedicated server for as low as 40 Euros