MySQL Triggers Explained: Creation, Usage & Optimization

目次

1. Introduction

What is a MySQL Trigger?

A MySQL trigger is a process that is automatically executed when a specific data operation (INSERT, UPDATE, DELETE) occurs.
Normally, SQL queries need to be executed manually, but by setting up a trigger, the database automatically executes specific actions.

For example, you can implement processes such as recording the change history in a log table when customer information is updated, or automatically adjusting inventory when order data is added, by using triggers.

Uses and Benefits of Triggers

MySQL triggers provide the following benefits in database operations.

Automatically Maintain Data Integrity

By utilizing triggers, you no longer need to manually manage the integrity of related data.
For example, you can introduce a mechanism to automatically create backups of deleted data.

Automatic Logging

You can create a log table to record data change history and use triggers to automatically save the change details.
This allows you to track who changed the data and when.

Automation of Data Processing

When a specific event occurs, you can automatically execute predefined processes.
For example, executing a process to reduce inventory quantity when a new order is added simplifies database maintenance.

Consistent Application of Business Rules

By using triggers, specific processes are always executed during data operations, allowing consistent application of business rules.
For example, you can implement validation on the database side to prevent negative values from being entered.

Reasons to Learn Triggers

Triggers are a very powerful tool in application development and data management.
In particular, the use of triggers is recommended in the following scenarios.

  • Enhancing Data Integrity: By automatically updating other related data when a data change occurs, you can maintain data consistency.
  • Simplifying Log Management: Instead of manually recording data change history, by using triggers to automatically record it, you can reduce management workload.
  • Preventing Data Inconsistencies: To prevent invalid data from being entered, you can use triggers to validate input data.

In this way, by utilizing triggers, database management becomes more efficient, and system reliability can be improved.

2. Basics of MySQL Triggers

Components of Triggers

MySQL triggers are a mechanism that automatically executes SQL in response to specific data operations (INSERT, UPDATE, DELETE).
Basically, triggers consist of the following three elements.

1. Event (Trigger Timing)

Triggers are triggered by the following data manipulation events.

  • INSERT: When new data is added
  • UPDATE: When existing data is modified
  • DELETE: When data is deleted

2. Timing (BEFORE / AFTER)

Triggers can execute processing before (BEFORE) or after (AFTER) the target data operation is executed.

  • BEFORE Trigger
  • Executed before INSERT, UPDATE, DELETE
  • Applied to data validation or prohibiting changes, etc.
  • Example: Prevent invalid data input (e.g., prohibit negative values)
  • AFTER Trigger
  • Executed after INSERT, UPDATE, DELETE
  • Used for logging or updating related tables
  • Example: Save change history to a log table

3. Scope of Application (Row Level / Statement Level)

  • Row-Level Trigger (FOR EACH ROW)
  • The trigger is executed for each row that is operated on (MySQL supports only row level)
  • Example: If multiple rows are updated with UPDATE, the trigger is executed for each row
  • Statement-Level Trigger (Not supported in MySQL)
  • The trigger fires only once when a single INSERT or UPDATE is executed (not supported in MySQL)

Types of Triggers and How to Use Them

By combining triggers, you can define 6 types of triggers.

Type of TriggerEventTimingMain Uses
BEFORE INSERTINSERTBeforeData validation (preventing invalid values)
AFTER INSERTINSERTAfterLogging, creating backups
BEFORE UPDATEUPDATEBeforeChecking update data, applying restrictions
AFTER UPDATEUPDATEAfterRecording change history, synchronizing other tables
BEFORE DELETEDELETEBeforeBacking up data before deletion
AFTER DELETEDELETEAfterRecording deletion history

Specific Usage Examples

1. Using a BEFORE INSERT Trigger to Prevent Invalid Data

CREATE TRIGGER prevent_negative_salary
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
  IF NEW.salary < 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Salary cannot be a negative value';
  END IF;
END;

How this trigger works

  • Prevents the input of negative values (error handling)

2. Using an AFTER INSERT Trigger to Record Logs

CREATE TRIGGER log_new_user
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO user_logs (user_id, action, timestamp)
  VALUES (NEW.id, 'Registration', NOW());
END;

How this trigger works

  • Every time a new user is added to the users table, it records the registration history in the user_logs table.

Differences Between Triggers and Stored Procedures

ItemTriggerStored Procedure
Execution MethodExecuted automaticallyExecuted explicitly with CALL
Main UsesAutomatic processing on data changesComplex SQL processing used repeatedly
Return ValueNoneHas return value
Transaction ControlNot possiblePossible

Summary

  • MySQL triggers are a mechanism that automatically executes SQL during data operations
  • There are two types of triggers: BEFORE and AFTER, with different uses depending on the execution timing
  • Only row-level triggers (FOR EACH ROW) are supported
  • Unlike stored procedures, triggers are executed automatically

3. How to Create Triggers

Prerequisites for Creating Triggers

Before creating a trigger in MySQL, you need to check the following points.

1. Checking Permissions

To create a trigger, you need MySQL’s SUPER privilege or TRIGGER privilege.
If you don’t have the privileges, grant them with the following command (requires administrator privileges).

GRANT SUPER, TRIGGER ON *.* TO 'username'@'host';
FLUSH PRIVILEGES;

* Note that on shared or rented servers, the SUPER privilege may be restricted.

2. Table Existence

Triggers can only be created for existing tables.
If the target table doesn’t exist, create it in advance.

3. MySQL Version

Triggers are available in MySQL 5.0.2 and later.
To check the version, execute the following SQL.

SELECT VERSION();

Basic CREATE TRIGGER Syntax

To create a trigger in MySQL, use the CREATE TRIGGER statement.

Syntax

CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
  -- SQL to execute
END;
  • {BEFORE | AFTER} → Trigger execution timing
  • {INSERT | UPDATE | DELETE} → Which event to execute on
  • ON table_name → Table to apply the trigger to
  • FOR EACH ROWRow-level trigger (required in MySQL)

Practical Examples of Creating Triggers

1. BEFORE INSERT Trigger (Preventing Invalid Data)

CREATE TRIGGER prevent_negative_salary
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
  IF NEW.salary < 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Salary cannot be negative';
  END IF;
END;

How This Trigger Works

  • When a negative value is entered in the salary column, it generates an error to prevent registration.

2. AFTER INSERT Trigger (Automatic Logging)

CREATE TRIGGER log_new_user
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO user_logs (user_id, action, timestamp)
  VALUES (NEW.id, 'registration', NOW());
END;

How This Trigger Works

  • Every time a new user is added to the users table, it records the registration history in the user_logs table.

3. AFTER UPDATE Trigger (Saving Change History)

CREATE TRIGGER track_salary_changes
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
  INSERT INTO salary_history (employee_id, old_salary, new_salary, changed_at)
  VALUES (OLD.id, OLD.salary, NEW.salary, NOW());
END;

How This Trigger Works

  • When the salary column in the employees table is changed, it records the before and after information in the history table.

Managing Triggers

Obtaining a List of Registered Triggers

SHOW TRIGGERS FROM database_name;
  • Specify the target database name for database_name.

Searching for Triggers Related to a Specific Table

SELECT * FROM information_schema.TRIGGERS
WHERE EVENT_OBJECT_TABLE = 'employees';

Deleting Triggers

How to Delete a Trigger

DROP TRIGGER IF EXISTS trigger_name;

For example, to delete the log_new_user trigger:

DROP TRIGGER IF EXISTS log_new_user;

Summary

  • To create a trigger, you need SUPER or TRIGGER privileges
  • Using CREATE TRIGGER, you can automatically execute processing at specific data operations
  • BEFORE triggers are used for data validation and preventing changes
  • AFTER triggers are used for logging and saving change history
  • Triggers can be managed with SHOW TRIGGERS and DROP TRIGGER

4. Practical Examples of Using MySQL Triggers

MySQL triggers are very useful for implementing automatic data processing.
Here, we introduce specific usage examples that are useful in actual system development and data management.

1. Automatic Data Synchronization (Backup)

To maintain data integrity, it is possible to automatically synchronize changes in one table to another table.
For example, create a trigger that creates a backup in order_backup when a new order is added to the orders table.

✅ Example: Back up data with AFTER INSERT

CREATE TRIGGER sync_orders
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_backup (order_id, user_id, total_price, created_at)
  VALUES (NEW.id, NEW.user_id, NEW.total, NOW());
END;

How this trigger works

  • When a new order is added to the orders table, data is automatically saved to order_backup.

2. Automatic Data Validation (Blocking Invalid Data)

To maintain data integrity, you can use triggers to prevent input of invalid values.
For example, control the inventory (inventory management) table so that stock does not become a negative value.

✅ Example: Prevent invalid data with BEFORE INSERT

CREATE TRIGGER prevent_negative_stock
BEFORE INSERT ON inventory
FOR EACH ROW
BEGIN
  IF NEW.stock < 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Stock quantity is negative. Please enter a correct value.';
  END IF;
END;

How this trigger works

  • If a negative value is entered into the inventory table, an error is raised to prevent registration.

3. User Activity Log Management

By utilizing triggers, you can automatically record user actions.
For example, you can set it to record a log when a new user is registered.

✅ Example: Automatically record log with AFTER INSERT

CREATE TRIGGER log_user_activity
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO user_logs (user_id, action, timestamp)
  VALUES (NEW.id, 'registration', NOW());
END;

How this trigger works

  • When a new user is added to the users table, a record is left in the log table.

4. Notifications on Data Changes (Email Notifications or Webhook Integration)

While MySQL alone cannot send email notifications directly,
you can achieve notifications by using triggers to detect data changes and execute stored procedures.

✅ Example: Call stored procedure with AFTER UPDATE

CREATE TRIGGER notify_stock_update
AFTER UPDATE ON inventory
FOR EACH ROW
BEGIN
  CALL send_stock_alert(NEW.product_id, NEW.stock);
END;

How this trigger works

  • When the stock (stock quantity) of inventory is updated, the send_stock_alert stored procedure is called.

5. Data Integration with Other Tables

You can also use triggers to automatically link multiple tables within the database.

✅ Example: Save employee salary history with AFTER UPDATE

CREATE TRIGGER track_salary_changes
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
  INSERT INTO salary_history (employee_id, old_salary, new_salary, changed_at)
  VALUES (OLD.id, OLD.salary, NEW.salary, NOW());
END;

How this trigger works

  • When the salary (salary) of the employees table is updated, record the old salary and new salary in the salary_history table.

Summary

  • Triggers are ideal for automatic data processing and can be widely used for backups, data validation, log management, etc.
  • Using AFTER triggers makes it possible to record change history and integrate with external systems.
  • By utilizing BEFORE triggers, you can prevent the registration of invalid data.
  • By combining with stored procedures, you can implement more advanced data processing and notification functions.

5. Precautions When Using Triggers

MySQL triggers are a very convenient feature for maintaining data integrity and performing automatic processing, but if not designed and managed properly, they can lead to performance degradation and debugging difficulties.
Here, we will explain in detail the important precautions when using triggers.

1. Impact on Performance

Triggers are automatically executed for each database operation, so if not managed properly, they can cause performance degradation.

✅ Issues

  • Too many triggers can slow down data operation processing speed
  • Nested triggers (calling another trigger within a trigger) can cause unintended load
  • When updating large amounts of data, multiple trigger firings can delay processing

✅ Improvements

  • Avoid creating unnecessary triggers
  • Aim for simple processing (manage complex logic with stored procedures)
  • Apply indexes to tables to optimize query processing speed

2. Risk of Deadlocks

Using triggers can lead to deadlocks (a state where multiple transactions hold locks on each other and processing stops).

✅ Example: Deadlock Caused by Trigger

CREATE TRIGGER update_stock
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
  UPDATE inventory SET stock = stock - NEW.quantity WHERE product_id = NEW.product_id;
END;

This trigger, when executed, can cause conflicts between updates to the orders table and the inventory table, potentially leading to deadlocks.

✅ Improvements

  • Use BEFORE triggers to optimize changes (less lock impact than AFTER)
  • Minimize queries within triggers and manage complex processing with stored procedures
  • Standardize transaction order to avoid lock conflicts
  • Reduce the number of records targeted for updates as much as possible

3. Constraints and Limitations of Triggers

MySQL triggers have several constraints and limitations.

✅ Transaction Control (COMMIT/ROLLBACK) Not Possible

  • COMMIT or ROLLBACK cannot be used within triggers
    → If an error occurs within a trigger, the entire processing including the trigger will be rolled back.

✅ Multiple Triggers of the Same Type Cannot Be Created for One Table

  • In MySQL, multiple triggers for the same event (e.g., AFTER INSERT) cannot be defined on one table
    → For example, attempting to create two AFTER INSERT triggers will result in an error.

🚨 Improvements:

  • Integrate trigger processing into one and implement branching logic

4. Debugging Triggers Is Difficult

Triggers operate in the database background, so even if errors occur, direct messages may not be displayed.

✅ Debugging Methods

  1. Create a log table to save trigger execution history
CREATE TABLE trigger_logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  event_type VARCHAR(50),
  message TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
  1. Use INSERT within the trigger to record the processing flow
CREATE TRIGGER debug_trigger
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO trigger_logs (event_type, message)
  VALUES ('INSERT', CONCAT('New user added: ', NEW.username));
END;

Using this method allows you to check trigger execution results→Execute SELECT * FROM trigger_logs; to view the logs.

5. Cases Where Triggers Should Be Used and Should Not Be Used

Triggers are convenient, but they should not be applied in all situations.

✅ Cases Where Triggers Should Be Used

  • Processing to ensure data integrity
  • Automatic recording of change history or logs
  • Data validation (preventing invalid data)

🚫 Cases Where Triggers Should Not Be Used

  • Cases requiring complex calculations or logic (stored procedures are more suitable)
  • Cases where triggers update many tables (performance degradation)
  • Cases requiring transaction control (COMMIT / ROLLBACK cannot be used within triggers)

Summary

  • Improper use of triggers can lead to performance degradation
  • To prevent deadlocks, consider using BEFORE triggers and transaction management
  • Understand MySQL’s constraints (no transaction control, cannot create multiple triggers of the same type)
  • Since debugging is difficult, use log tables to record the processing flow
  • It is important to discern cases where triggers are suitable and where they are not

6. Frequently Asked Questions (FAQ)

This section summarizes frequently asked questions about MySQL triggers.
It covers practical information from basic usage to troubleshooting.

Q1. What is the difference between triggers and stored procedures?

A.

AspectTriggerStored Procedure
Execution MethodAutomatic execution (on data change)Manual execution (CALL procedure_name)
Main UseAutomatic processing on data changesAutomation of repeatedly used SQL
Return ValueNoneHas return value
Transaction ControlNot possiblePossible

Key Points for Differentiation

  • Triggers are suitable for “processing that must always be executed on data changes”
  • Examples: Logging, ensuring data integrity, saving change history
  • Stored procedures are suitable for “cases where you want to manually execute specific operations”
  • Examples: Batch processing, aggregation processing, updating large amounts of data

Q2. Can I set multiple triggers on one table in MySQL?

A. Yes, it is possible, but there are restrictions.
Restrictions:

  • You cannot create multiple triggers with the same event and timing (e.g., AFTER INSERT)
  • For example, trying to set the following two AFTER INSERT triggers on the users table will result in an error.
  CREATE TRIGGER trigger1 AFTER INSERT ON users FOR EACH ROW BEGIN ... END;
  CREATE TRIGGER trigger2 AFTER INSERT ON users FOR EACH ROW BEGIN ... END;
  • MySQL allows only one AFTER INSERT trigger.

Solution:

  • Combine into one trigger and implement multiple processes using conditional branching (IF)
  CREATE TRIGGER manage_user_insert
  AFTER INSERT ON users
  FOR EACH ROW
  BEGIN
    -- Record the log
    INSERT INTO user_logs (user_id, action, timestamp)
    VALUES (NEW.id, 'registration', NOW());

    -- Grant first-time login bonus
    IF NEW.is_new = 1 THEN
      INSERT INTO bonuses (user_id, amount) VALUES (NEW.id, 1000);
    END IF;
  END;

Q3. How do I debug MySQL triggers?

A.
Triggers cannot be checked with SELECT like regular SQL, so debugging is difficult.
Using a log table is a common method for debugging.

Create a log table for debugging

CREATE TABLE trigger_logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  message TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Record logs using INSERT inside the trigger

CREATE TRIGGER debug_trigger
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO trigger_logs (message)
  VALUES (CONCAT('New user added: ', NEW.username));
END;

Check the logs

SELECT * FROM trigger_logs;

📌This allows you to confirm if the trigger is working correctly.

Q4. Do triggers affect performance?

A. Yes, especially in large-scale databases, caution is needed.
Main Causes of Impact

  • If triggers are executed frequently, data operations (INSERT / UPDATE / DELETE) will slow down
  • Performing complex processing inside triggers (such as updating other tables or calculations) increases query load
  • Trigger nesting (where another trigger fires inside a trigger) can cause unintended delays

Measures for Performance Optimization

  1. Do not create unnecessary triggers (handle on the application side if possible)
  2. Keep processing simple (separate complex calculations or conditional branching into stored procedures)
  3. Set appropriate indexes to improve the execution speed of queries inside triggers
  4. Use BEFORE triggers to validate data before changes, reducing unnecessary processing

Summary

  • Triggers are convenient for automatic data processing, but it’s important to differentiate their use from stored procedures and views
  • In MySQL, you cannot create multiple triggers of the same type on one table
  • Debugging can be done easily by utilizing log tables
  • To prevent performance degradation, it is recommended to design triggers simply
  • Since triggers cannot be modified, deletion and recreation are necessary

7. Summary

MySQL triggers are a very powerful tool that enables automatic processing in the database and maintains data integrity.
In this article, we have explained in detail from the basics of triggers to creation methods, usage examples, precautions, and FAQ.

Below, we review the important points of MySQL triggers.

1. Overview of MySQL Triggers

  • What are triggers?
  • A mechanism that automatically executes SQL when specific data operations (INSERT, UPDATE, DELETE) occur
  • Uses of Triggers
  • Maintaining data integrity, log management, automatic processing when data changes, etc.
  • Types of Triggers
  • BEFORE Triggers (executed before data changes)
  • AFTER Triggers (executed after data changes)

2. How to Create Triggers

  • Use CREATE TRIGGER to set up triggers according to data operations on the target table
  • Example: Recording logs with AFTER INSERT
CREATE TRIGGER log_new_user
AFTER INSERT ON users
FOR EACH ROW
BEGIN
  INSERT INTO user_logs (user_id, action, timestamp)
  VALUES (NEW.id, 'registration', NOW());
END;
  • You can check created triggers with SHOW TRIGGERS and delete them with DROP TRIGGER

3. Usage Examples of Triggers

  • Automatic Data Synchronization (Backup)
  • Automatically save data from the orders table to order_backup
  • Automatic Data Validation
  • Use BEFORE INSERT to prevent input of negative values
  • Log Management
  • Record user activity in user_logs with AFTER INSERT
  • Notifications and Integration with External Systems
  • Implement email notifications by calling stored procedures with AFTER UPDATE
  • Saving Change History
  • Record before and after change data in salary_history with AFTER UPDATE

4. Precautions When Using Triggers

  • Impact on Performance
  • If there are too many triggers, the processing speed of data operations decreases
  • Be careful with nested triggers (where another trigger fires within a trigger)
  • Risk of Deadlocks
  • Utilize BEFORE triggers to avoid lock contention
  • Constraints of Triggers
  • Cannot control transactions (COMMIT / ROLLBACK)
  • Cannot set multiple triggers of the same type on one table
  • Debugging Methods
  • Create a log table and record the execution history of triggers
  • Check settings with SHOW TRIGGERS or information_schema.TRIGGERS

5. Frequently Asked Questions (FAQ)

Q. What is the difference between stored procedures and triggers in MySQL?Triggers are automatically executed during data operations, while stored procedures are executed manually.

Q. Do MySQL triggers affect performance?Yes, they do. For optimization, it’s important not to create unnecessary triggers, keep processing simple, and apply indexes.Q. How to debug triggers?It’s common to create a log table and record the processing during trigger execution.

INSERT INTO trigger_logs (message) VALUES ('Trigger executed');

Q. Can you modify triggers?You cannot modify them directly, so you need to drop them with DROP TRIGGER and create a new one.

Summary

✔ Advantages of MySQL Triggers

Automatically maintain data integrityReduce manual processing and improve database management efficiencyEasy management of data change historyMore advanced processing is possible by combining with stored procedures

❗ Precautions for MySQL Triggers

If there are too many triggers, it affects performanceSince debugging is difficult, it’s necessary to use log tablesConsider the impact on transactions and design to avoid deadlocksMySQL triggers can significantly improve data management when used appropriately.
Refer to this article to design effective triggers and aim for more optimal database operations!