MySQL Triggers

Learn via video courses
Topics Covered

Overview

Triggers in MySQL are special stored programs that are executed automatically in response to certain events or actions performed on a table, such as inserting, updating, or deleting data. Let's see further about trigger in MySql in this article.

Syntax

The syntax for creating a trigger in MySQL is as follows:

Introduction

Triggers in MySQL are special stored programs that are associated with a specific table and automatically executed in response to certain events or actions performed on that table. Triggers can also be defined to execute either once for each triggering statement or once for each row affected by the statement. Once a trigger is defined, it will automatically execute whenever the specified event occurs on the associated table.

For example:

MySQL Trigger Types

Triggers can be used to enforce business rules, implement complex constraints, audit changes to data, and perform other database operations. MySQL supports four types of triggers:

  • BEFORE Trigger: A BEFORE trigger is a type of trigger that is executed before an INSERT, UPDATE, or DELETE operation is performed on a table. Syntax:

  • AFTER Trigger: An AFTER trigger is executed after an INSERT, UPDATE, or DELETE operation is performed on a table.

    Syntax:

  • INSTEAD OF Trigger: An INSTEAD OF trigger is a type of trigger that allows you to define custom logic that replaces the standard behavior of an INSERT, UPDATE, or DELETE statement on a view. It is commonly used with views and allows you to perform a custom operation instead of the default view operation. Syntax:

  • COMPOUND Trigger: A COMPOUND trigger combines both BEFORE and AFTER triggers. A COMPOUND trigger is useful when you need to perform a series of actions that span both the BEFORE and AFTER execution of the trigger.

    Syntax:

Row-Level Trigger

A row-level trigger in MySQL is a type of trigger that is executed once for each row that is affected by the triggering event. This means that if a single event causes multiple rows to be affected, the trigger will be fired once for each affected row.

Row-level triggers can be used to perform actions such as auditing, data validation, or data transformation on a per-row basis.

Statement-Level Trigger

A statement-level trigger in MySQL is a type of trigger that is executed once for each statement that is executed on the table it is attached to.

When a trigger is created on a table, it is associated with a specific event, such as an INSERT, UPDATE, or DELETE operation. The trigger then executes automatically when the associated event occurs on the table.

Statement-level triggers are different from row-level triggers in that they operate on the entire result set of the statement, rather than on individual rows within the result set.

Syntax

Why do We Need Triggers in MySQL?

  • Triggers automate database tasks.
  • They can be used to enforce business rules and implement complex constraints.
  • Triggers can audit changes to data and perform other database operations.
  • They can help ensure that data in the database remains consistent and accurate.
  • Triggers can update a timestamp column automatically when a row is modified or prevent certain changes to data based on business rules.

Advantages of Triggers

Some advantages of using triggers in a MySQL database include:

  • Ensuring Data Integrity: Triggers can help prevent data inconsistencies and errors that can occur due to manual data entry or application programming mistakes.
  • Automating Tasks: Triggers can save time and reduce errors by eliminating the need for manual intervention.
  • Providing a Security Mechanism: Triggers can be used to enhance database security by restricting access to data or by ensuring that only authorized changes are made to the data.
  • Simplifying Data Management: Triggers can simplify database management by providing an easy way to maintain complex business rules, data transformations, or synchronization tasks.

Disadvantages of Triggers

Some disadvantages of using triggers in a MySQL database include:

  • Performance Impact: Triggers can slow down data processing and database response times, which can be a problem in high-volume environments.
  • Complexity: The complexity of triggers can increase the likelihood of errors or mistakes that can cause data inconsistencies or other problems.
  • Debugging: It can be challenging to identify the source of errors or bugs in triggers, which can lead to long troubleshooting times.
  • Security Risks: Triggers can potentially introduce security risks, particularly if they are used to bypass database security controls or to perform unauthorized actions on data.

Managing MySQL Triggers

Managing MySQL triggers involves creating, modifying, enabling, disabling, and dropping triggers as needed.

To demonstrate the use of triggers, we can use a sample dataset of a simple online bookstore. The database schema consists of two tables:

  • Books
  • Orders

The Books table contains information about available books, such as title, author, publisher, and price. The Orders table stores information about orders made by customers, including customer_name, book title, quantity, and order_date. Let's create the two tables and insert some sample data:

Create Triggers

Syntax:

For example:

Now, when a new book is inserted into the Books table without an ID specified, the trigger will automatically assign a new ID that is one greater than the current maximum ID in the table.

Drop Triggers

Syntax:

where,

  • IF EXISTS: An optional clause that specifies that the DROP TRIGGER statement should not generate an error if the trigger does not exist.

For example: To drop the auto_book_id trigger, we can use the following SQL command:

Create a BEFORE INSERT Trigger

Syntax:

For example: Suppose we want to automatically set the book ID for new orders in the Orders table, based on the maximum ID currently in the table.

This trigger will set the id field of a new row to be inserted into the Orders table to the maximum ID currently in the table plus one.

The trigger will automatically set the id field of the new order to 5 (the current maximum ID plus one):

Output:

Idcustomer_namebook_idquantityorder_date
5Amy Lee132023-03-28

Create an AFTER INSERT Trigger

Syntax:

For example: Suppose we want to update the Books table automatically after a new order is inserted into the Orders table, by decrementing the stock quantity of the book that was ordered.

This trigger will update the stock_quantity field of the book that was ordered, by subtracting the quantity of the new order from the current stock quantity. Now let's try to insert a new order for the book with ID 1:

The trigger will update the Books table automatically, by decrementing the stock quantity of the book with ID 1 by 1:

Output:

Idtitleauthorpublisherpricestock_quantity
1The Great GatsbyF. Scott FitzgeraldScribner12.991

Create a BEFORE UPDATE Trigger

Syntax:

For example: Suppose we want to prevent the price of a book from being updated to a negative value in the Books table.

This trigger will raise an error if the price of a book is being updated to a negative value, by using the SIGNAL statement to generate a custom error message. Now let's try to update the price of the book with ID 2 to -5:

The trigger will prevent the update and raise an error message:

Create an AFTER-UPDATE Trigger

Syntax:

For example: Suppose we want to update the Orders table automatically after a book's price is updated in the Books table, by recalculating the total cost of all orders for that book. We can create a trigger to do this as follows:

This trigger will update the total_cost field of all orders for the book that was updated, by multiplying the quantity of each order by the new price of the book. Now let's try to update the price of the book with ID 1 to 10:

The trigger will update the Orders table automatically, by recalculating the total cost of all orders for the book with ID 1:

Output:

Idcustomer_namebook_idquantityorder_date
1 John Doe122023-03-2520.98
4 Amy Lee132023-03-2829.97

Create a BEFORE DELETE Trigger

Syntax:

For example: Suppose we want to prevent a book from being deleted from the Books table if there are any orders for that book in the Orders table.

This trigger will raise an error if there are any orders for the book that is being deleted, by using the SIGNAL statement to generate a custom error message. Now let's try to delete the book with ID 2:

The trigger will prevent the deletion and raise an error message:

Create an AFTER DELETE Trigger

Syntax:

For example: Suppose we want to update the Orders table automatically after a book is deleted from the Books table, by deleting any orders for that book.

This trigger will delete all orders for the book that was deleted from the Books table. Now let's try to delete the book with ID 3:

The trigger will update the Orders table automatically, by deleting any orders for a book with ID 3:

Output:

Idcustomer_namebook_idquantityorder_datetotal_cost

As we can see, there are no orders for the book with ID 3 in the Orders table anymore.

Create Multiple Triggers for a Table That Have the Same Trigger Event and Time

We can create multiple triggers for a table that has the same trigger event and time in MySQL. You simply need to specify a unique name for each trigger.

For example: Creating multiple triggers for the Orders table that have the same trigger event and time:

In this example, we have created two triggers for the Orders table that both have the trigger event BEFORE INSERT and the time FOR EACH ROW. These triggers will automatically update the total_cost field of an order based on the price and quantity of the corresponding book whenever a new order is inserted or an existing order is updated.

Show Triggers

Syntax:

For example:

Output:

TriggerEventTimingCreatedsql_modeDefinercharacter_set_clientcollation_connectionDatabase Collation
update_order_total_before_insertINSERTBEFORE2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci
update_order_total_before_updateUPDATEBEFORE2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci
update_order_total_after_deleteDELETEAFTER2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci
set_default_publisher_before_insertINSERTBEFORE2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci
set_default_price_before_insertINSERTBEFORE2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci
set_default_stock_before_insertINSERTBEFORE2022-04-01 ...user@localhostutf8mb4utf8mb4_general_ciutf8mb4_unicode_ci

Naming Conventions

Naming conventions for triggers in MySQL are not strictly enforced, but it is recommended to follow some best practices to make your code more readable and maintainable.

Here are some common naming conventions for triggers in MySQL:

  • Use a descriptive name that explains the purpose of the trigger.
  • If you have multiple triggers for the same table and event, use a suffix or a numbering convention to distinguish them.
  • Avoid using keywords or special characters in trigger names.
  • Keep trigger names short and meaningful.

Conclusion

  • A trigger is a database object that is associated with a table and is automatically executed in response to certain events, such as INSERT, UPDATE, or DELETE statements.
  • There are four types of triggers in MySQL: BEFORE triggers, AFTER triggers, INSTEAD OF triggers, and COMPOUND triggers.
  • Triggers can be created using the CREATE TRIGGER statement.
  • Triggers can be disabled using the DISABLE TRIGGER statement, and re-enabled using the ENABLE TRIGGER statement.
  • It is important to be cautious when using triggers, as they can add significant overhead to database operations and make it more difficult to maintain and debug code.