search
HomeDatabaseMysql TutorialMySQL trigger usage

MySQL trigger usage

Dec 12, 2016 am 11:53 AM
mysql trigger

MySQL includes support for triggers. A trigger is a database object related to table operations. When a specified event occurs on the table where the trigger is located, the object will be called, that is, the operation event of the table triggers the execution of the trigger on the table.

Create a trigger
In MySQL, the syntax for creating a trigger is as follows:

CREATE TRIGGER trigger_name
trigger_time
trigger_event ON tbl_name
FOR EACH ROW
trigger_stmt

Among them:

trigger_name: identifies the trigger name, specified by the user;
trigger_time: identifies the triggering time, the value is BEFORE or AFTER;
trigger_event: identifies the trigger event, the value is INSERT, UPDATE or DELETE;
tbl_name: identifies the table name to create the trigger, that is, on which table the trigger is created;
trigger_stmt: trigger program body, which can be a SQL statement, or use BEGIN and END contain multiple statements.

It can be seen that 6 types of triggers can be created, namely: BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE, AFTER INSERT, AFTER UPDATE, AFTER DELETE.

Another limitation is that you cannot create 2 triggers of the same type on a table at the same time, so a maximum of 6 triggers can be created on a table.

trigger_event detailed explanation
MySQL except for INSERT, UPDATE, DELETE In addition to defining basic operations, it also defines LOAD DATA and REPLACE statements, which can also cause the triggering of the above 6 types of triggers.

The LOAD DATA statement is used to load a file into a data table, which is equivalent to a series of INSERT operations.

The REPLACE statement is generally very similar to the INSERT statement, except that when there is a primary key or unique index in the table, if the inserted data is different from the original When the primary key or unique index is consistent, the original data will be deleted first, and then a new piece of data will be added. In other words, a REPLACE statement is sometimes equivalent to one.

INSERT statement is sometimes equivalent to a DELETE statement plus an INSERT statement.

INSERT type trigger: The trigger is activated when a row is inserted, and may be triggered by INSERT, LOAD DATA, REPLACE statements;
UPDATE Type trigger: The trigger is activated when a certain row is changed, which may be triggered by the UPDATE statement;
DELETE type trigger: The trigger is activated when a certain row is deleted, which may be triggered by Triggered by DELETE and REPLACE statements.

BEGIN … END Detailed explanation
In MySQL, the syntax of the BEGIN … END statement is:

BEGIN
[statement_list]
END
Among them, statement_list Represents a list of one or more statements. Each statement in the list must be terminated with a semicolon (;).
In MySQL, the semicolon is the identifier of the end of the statement. Encountering a semicolon means that the statement has ended and MySQL can start execution. Therefore, the interpreter encounters statement_list Execution starts after the semicolon in , and then an error is reported because no END matching BEGIN is found.

The DELIMITER command will be used at this time (DELIMITER is the delimiter, which means separator). It is a command and does not require an end-of-statement identifier. The syntax is:
DELIMITER new_delemiter
new_delemiter It can be set to 1 or more length symbols. The default is semicolon (;). We can change it to other symbols, such as $:
DELIMITER $
The statement after this ends with a semicolon, and the interpreter will not react. Only when $ is encountered, the statement is considered to have ended. Note that after using it, we should remember to modify it back.

A complete example of creating a trigger
Suppose there are two tables in the system:
Class table class(class number classID, number of students in the class stuCount)
Student table student (student ID, classID)
To create a trigger to automatically update the number of students in the class table as students are added, the code is as follows:

DELIMITER $
create trigger tri_stuInsert after insert
on student for each row
begin
declare c int;
set c = (select stuCount from class where classID=new.classID);
update class set stuCount = c + 1 where classID = new.classID;
end$
DELIMITER ;

Detailed explanation of variables
Use DECLARE in MySQL to define a Local variable, this variable can only be used in BEGIN ... END It is used in compound statements and should be defined at the beginning of compound statements,

that is, before other statements. The syntax is as follows:

DECLARE var_name[,...] type [DEFAULT value]
where:
var_name is the variable name, the same as SQL The statements are the same, variable names are not case-sensitive; type is any data type supported by MySQL; multiple variables of the same type can be defined at the same time, separated by commas; the initial value of the variable is NULL, if necessary, you can use The DEFAULT clause provides a default value, which can be specified as an expression.

Use SET statement for variable assignment, the syntax is:

SET var_name = expr [,var_name = expr] ...

NEW and OLD detailed explanation

The NEW keyword is used in the above example, and in MS SQL Server INSERTED and DELETED are similar. NEW and DELETED are defined in MySQL. OLD, used to represent

In the table where the trigger is located, the row of data that triggered the trigger.
Specifically:
In INSERT type triggers, NEW Used to represent new data that will be (BEFORE) or has been (AFTER) inserted;
In UPDATE type triggers, OLD is used to represent the original data that will be or has been modified, NEW Used to represent new data that will be or has been modified;
In DELETE type triggers, OLD is used to represent the original data that will be or has been deleted;
Usage: NEW.columnName (columnName is a column name of the corresponding data table)
In addition, OLD is read-only, while NEW can use SET in triggers Assign a value so that the trigger will not be triggered again and cause a circular call (for example, before inserting a student, add "2013" before its student number).

Viewing triggers

is the same as viewing databases (show databases;) and viewing tables (show tables;). The syntax of viewing triggers is as follows:

SHOW TRIGGERS [FROM schema_name];
where, schema_name is the name of the Schema, In MySQL Schema and Database are the same, that is to say, you can specify the database name, so you don't have to "USE database_name;" first.

Delete triggers


Same as deleting databases and tables, the syntax of deleting triggers is as follows:

DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name

The execution order of triggers


The database we created It is generally an InnoDB database, and the tables created on it are transactional tables, that is, transaction safe. At this time, if the SQL statement or trigger fails to execute, MySQL The transaction will be rolled back, including:

① If the BEFORE trigger fails to execute, SQL cannot be executed correctly.

②When SQL execution fails, the AFTER trigger will not fire.

③AFTER If a trigger of type fails to execute, SQL will roll back.

Do you guys have some understanding of the use of mysql triggers? If you have any questions, please leave me a message and we can make progress together.

Statement
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
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.