Table of Contents
Trigger overview
Home Database Mysql Tutorial What level is mysql trigger?

What level is mysql trigger?

Mar 30, 2023 pm 08:05 PM
mysql trigger

Mysql triggers are row-level. According to SQL standards, triggers can be divided into two types: 1. Row-level triggers, which will be activated once for each row of data modified. If a statement inserts 100 rows of data, the trigger will be called 100 times; 2. Statement-level triggers The trigger is activated once for each statement. A statement that inserts 100 rows of data will only call the trigger once. MySQL only supports row-level triggers, not prepared statement-level triggers.

What level is mysql trigger?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Trigger overview

MySQL trigger is a stored procedure that is associated with a specified table. When the data in the table changes (Add, update, delete) automatically executed. These operations that modify data rows are called trigger events. For example, statements such as INSERT or LOAD DATA that insert data can activate insert triggers.

According to SQL standards, triggers can be divided into row-level triggers (row-level triggers) and statement-level triggers (statement-level triggers).

  • The row-level trigger will be activated once for each row of data modified. If a statement inserts 100 rows of data, the trigger will be called 100 times;

  • Statement-level triggers are activated once for each statement. A statement that inserts 100 rows of data will only call the trigger once.

  • #MySQL only supports row-level triggers and does not support prepared statement-level triggers.

What level is mysql trigger?

Different events can activate different types of triggers. The INSERT event trigger is used for inserting data operations, including INSERT, LOAD DATA, REPLACE statements, etc.; the UPDATE event trigger is used for update operations, such as UPDATE statements; the DELETE event trigger is used for delete operations, such as DELETE and REPLACE statements, etc., DROP TABLE and The TRUNCATE TABLE statement does not activate delete triggers.

In addition, MySQL triggers can be executed before or after the triggering event, which are called BEFORE triggers and AFTER triggers respectively. These two trigger timings can be combined with different trigger events, such as BEFORE INSERT trigger or AFTER UPDATE trigger.

The advantages of MySQL triggers include:

  • Record and audit user modification operations on data in the table to achieve auditing functions;

  • Implement integrity constraints that are more complex than check constraints, such as prohibiting data operations during non-business hours;

  • Implement certain business logic, such as adding or Automatically update the number of people in the department when deleting employees;

  • Synchronously replicate the data in the table in real time.

Although triggers are powerful, they also have some shortcomings:

  • Triggers will increase the database structure Complexity, and triggers are invisible to the application and difficult to debug;

  • Triggers need to occupy more database server resources. Try to use non-null, unique, and check constraints provided by the database. etc;

  • Triggers cannot receive parameters and can only operate based on the current trigger object.

Using triggers for special scenarios can bring certain convenience; but do not rely too much on triggers to avoid database performance degradation and maintenance difficulties. Next we introduce the management operations of triggers.

Three triggers supported by MySQL

In actual use, MySQL supports three triggers: INSERT trigger, UPDATE triggers and DELETE triggers.

1) INSERT trigger

A trigger that responds before or after the INSERT statement is executed.

You need to pay attention to the following points when using INSERT triggers:

  • In the INSERT trigger code, you can reference a virtual table named NEW (case-insensitive) to access the inserted row.

  • In the BEFORE INSERT trigger, the value in NEW can also be updated, which allows the inserted value to be changed (as long as it has the corresponding operation permissions).

  • For the AUTO_INCREMENT column, NEW contains the value 0 before the INSERT is executed and will contain the new automatically generated value after the INSERT is executed.

2) UPDATE trigger

A trigger that responds before or after the UPDATE statement is executed.

You need to pay attention to the following points when using UPDATE triggers:

  • In the UPDATE trigger code, you can reference a virtual table named NEW (case-insensitive) to access the updated value.

  • Within the UPDATE trigger code, a virtual table named OLD (case-insensitive) can be referenced to access the value before the UPDATE statement was executed.

  • In the BEFORE UPDATE trigger, the value in NEW may also be updated, which allows changing the value to be used in the UPDATE statement (as long as you have the corresponding operation permissions).

    All values ​​in
  • OLD are read-only and cannot be updated.

Note: When the trigger is designed to trigger the update operation of the table itself, only BEFORE type triggers can be used, and AFTER type triggers will not be allowed.

3) DELETE trigger

A trigger that responds before or after the DELETE statement is executed.

You need to pay attention to the following points when using DELETE triggers:

  • In the DELETE trigger code, you can reference a virtual table named OLD (case-insensitive) to access deleted rows. All values ​​in

  • OLD are read-only and cannot be updated.

Generally speaking, during the use of triggers, MySQL will handle errors in the following ways.

For transactional tables, if the trigger program fails, and the resulting entire statement fails, all changes performed by the statement will be rolled back; for non-transactional tables, such rollback cannot be performed , even if the statement fails, any changes made before the failure are still effective.

If the BEFORE trigger fails, MySQL will not perform the operation on the corresponding row.

If an error occurs during the execution of the BEFORE or AFTER trigger program, the entire statement calling the trigger program will fail.

MySQL will execute the AFTER trigger only if both the BEFORE trigger and the row operation have been successfully executed.

Create trigger

MySQL uses the CREATE TRIGGRT statement to create a trigger. The basic syntax is as follows:

CREATE TRIGGER trigger_name
    { BEFORE | AFTER } { INSERT | UPDATE | DELETE }
    ON table_name FOR EACH ROW
    trigger_body;
Copy after login

Among them, trigger_name is the name of the trigger; BEFORE and AFTER are used to specify the triggering time of the trigger; INSERT, UPDATE and DELETE are used to define the type of triggering event; table_name is the name of the table associated with the trigger, which cannot be a temporary table or view; FOR EACH ROW Indicates that this is a row-level trigger; trigger_body is the specific statement executed by the trigger.

For example, since employees’ salaries are important information, the salary modification history needs to be recorded. First, we create an audit table:

CREATE TABLE emp_salary_audit (
    audit_id    INTEGER NOT NULL AUTO_INCREMENT
    emp_id      INTEGER NOT NULL,
    old_salary  NUMERIC(8,2) NULL,
    new_salary  NUMERIC(8,2) NULL,
    change_date TIMESTAMP NOT NULL,
    change_by   VARCHAR(50) NOT NULL,
    CONSTRAINT pk_emp_salary_audit PRIMARY KEY (audit_id)
);
Copy after login

Among them, audit_id is the auto-increment primary key; emp_id is the employee number; old_salary and new_salary are used to store the monthly salary before and after modification respectively; change_date records the modification time; change_by The user who performed the modification operation is recorded.

Then create a trigger tri_audit_salary, which is used to record the modification record of employees’ monthly salary:

DELIMITER $$
CREATE TRIGGER tri_audit_salary
  AFTER UPDATE ON employee
  FOR EACH ROW
BEGIN
  -- 当月薪改变时,记录审计数据
  IF (NEW.salary <> OLD.salary) THEN
   INSERT INTO salary_audit (emp_id, old_salary, new_salary, change_date, change_by)
   VALUES(OLD.emp_id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP, USER());
  END IF;
END$$
DELIMITER ;
Copy after login

Among them, DELIMITER is used to modify the end character of the SQL statement, which we already have when introducing the stored procedure. As you know; AFTER means executing the trigger after modifying the data; UPDATE means recording data changes only for update operations; NEW and OLD in the trigger body are special variables in MySQL triggers, including records after modification and before modification. There is no OLD variable for the INSERT trigger, and there is no NEW variable for the DELETE trigger; CURRENT_TIMESTAMP and USER() are MySQL system functions that return the current time and logged-in user.

After creating the trigger, we perform some data modification operations to verify the effect of the trigger:

UPDATE employee
SET email = &#39;sunqian@shuguo.net&#39;
WHERE emp_name = &#39;孙乾&#39;;

UPDATE employee
SET salary = salary * 1.1
WHERE emp_name = &#39;孙乾&#39;;

SELECT *
FROM salary_audit;
audit_id|emp_id|old_salary|new_salary|change_date        |change_by|
--------|------|----------|----------|-------------------|---------|
       1|    25|      4700|      5170|2019-10-18 10:16:36|TONY     |
Copy after login

The first UPDATE statement only modified the email address of "Sun Qian", so Tri_audit_salary will not be triggered; the second UPDATE statement modifies his monthly salary, triggering tri_audit_salary. Therefore, the audit table salary_audit contains a piece of data that records the situation before and after the monthly salary change.

If you want to audit the operations of adding employees and deleting employees at the same time, you can create an INSERT trigger and a DELETE trigger.

In addition, MySQL supports defining multiple triggers for the same triggering timing and the same event, and specifying their execution order:

CREATE TRIGGER trigger_name
    { BEFORE | AFTER } { INSERT | UPDATE | DELETE }
    ON table_name FOR EACH ROW
    { FOLLOWS | PRECEDES } other_trigger
    trigger_body;
Copy after login

Among them, FOLLOWS indicates that the trigger is in The trigger is executed after other_trigger; PRECEDES indicates that the trigger is executed before other_trigger; if no options are specified, by default, the triggers are executed in the order in which they are created.

View triggers

Use the SHOW TRIGGERS statement to view the list of triggers in the database:

SHOW TRIGGERS
    [{FROM | IN} db_name]
    [LIKE &#39;pattern&#39; | WHERE expr]
Copy after login

Among them, db_name Used to view triggers in the specified database, the default is the current database; LIKE is used to match the name of the stored procedure, and WHERE can specify more filter conditions. For example, the following statement returns the triggers in the current database:

mysql> show triggers\G
*************************** 1. row ***************************
             Trigger: tri_audit_salary
               Event: UPDATE
               Table: employee
           Statement: BEGIN
  -- 当月薪改变时,记录审计数据
  IF (NEW.salary <> OLD.salary) THEN
   INSERT INTO salary_audit (emp_id, old_salary, new_salary, change_date, change_by)
   VALUES(OLD.emp_id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP, USER());
  END IF;
END
              Timing: AFTER
             Created: 2020-10-06 21:50:02.47
            sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
             Definer: root@localhost
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
  Database Collation: utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
Copy after login

In addition, the MySQL system table INFORMATION_SCHEMA.TRIGGERS contains more detailed trigger information.

If you want to get the DDL statement that creates a trigger, you can SHOW CREATE TRIGGER statement. For example:

mysql> SHOW CREATE TRIGGER tri_audit_salary\G
*************************** 1. row ***************************
               Trigger: tri_audit_salary
              sql_mode: STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
SQL Original Statement: CREATE DEFINER=`root`@`localhost` TRIGGER `tri_audit_salary` AFTER UPDATE ON `employee` FOR EACH ROW BEGIN
  -- 当月薪改变时,记录审计数据
  IF (NEW.salary <> OLD.salary) THEN
   INSERT INTO salary_audit (emp_id, old_salary, new_salary, change_date, change_by)
   VALUES(OLD.emp_id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP, USER());
  END IF;
END
  character_set_client: utf8mb4
  collation_connection: utf8mb4_0900_ai_ci
    Database Collation: utf8mb4_0900_ai_ci
               Created: 2020-10-06 21:50:02.47
1 row in set (0.00 sec)
Copy after login

Delete trigger

MySQL does not provide a statement to modify a trigger. You can only delete and create a trigger again through the DROP TRIGGER statement. device. For example, the following statement can be used to delete the trigger tri_audit_salary:

DROP TRIGGER IF EXISTS tri_audit_salary;
Copy after login

IF EXISTS avoids an error if the trigger tri_audit_salary does not exist.

[Related recommendations: mysql video tutorial]

The above is the detailed content of What level is mysql trigger?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

Navicat connects to database error code and solution Navicat connects to database error code and solution Apr 08, 2025 pm 11:06 PM

Common errors and solutions when connecting to databases: Username or password (Error 1045) Firewall blocks connection (Error 2003) Connection timeout (Error 10060) Unable to use socket connection (Error 1042) SSL connection error (Error 10055) Too many connection attempts result in the host being blocked (Error 1129) Database does not exist (Error 1049) No permission to connect to database (Error 1000)

See all articles