Home Database Mysql Tutorial What is a trigger in mysql

What is a trigger in mysql

Jun 14, 2022 am 11:53 AM
mysql

In MySQL, a trigger is a set of SQL statements stored in the database directory that are executed or fired whenever an event associated with a table occurs, such as an insert, update, or delete. Triggers are closely related to data tables and are mainly used to protect the data in the tables; especially when there are multiple tables with certain interconnections, triggers can maintain data consistency in different tables. In MySQL, triggers can only be activated when executing INSERT, UPDATE, and DELETE operations, and other SQL statements will not activate triggers.

What is a trigger in mysql

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

Triggers in mysql

In mysql, a trigger is a set of SQL statements stored in the database directory. Whenever A trigger is executed or fired when an event associated with the table occurs, such as an insert, update, or delete.

MySQL triggers, like stored procedures, are programs embedded in MySQL and are powerful tools for data management in MySQL. The difference is that the execution of a stored procedure requires a CALL statement, while the execution of a trigger does not require a CALL statement or manual startup. Instead, it is triggered and activated through related operations on the data table to achieve execution. For example, its execution will be activated when an operation (INSERT, DELETE or UPDATE) is performed on the student table.

Triggers are closely related to data tables and are mainly used to protect the data in the tables. Especially when there are multiple tables that are related to each other, triggers can maintain data consistency in different tables.

In MySQL, triggers can only be activated when performing INSERT, UPDATE, and DELETE operations. Other SQL statements will not activate triggers.

So why use triggers? For example, when actually developing projects, we often encounter the following situation:

  • When adding a record about students to the student table, the total number of students must change at the same time.

  • When adding a student record, you need to check whether the age meets the range requirements.

  • When deleting a student's information, you need to delete the corresponding record on the score sheet.

  • When deleting a piece of data, you need to keep a backup copy in the database archive table.

Although the business logic implemented in the above situations is different, they all need to automatically perform some processing when the data table changes. At this time, trigger processing can be used. For example, for the first case, you can create a trigger object and perform an operation to calculate the total number of students every time a student record is added. This ensures that every time a student record is added, the total number of students and the number of student records will be calculated. are consistent.

MySQL supported triggers

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

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, then all changes performed by the statement will be rolled back; for non-transactional tables, such rollback cannot be performed, even if the statement Failure, any changes made before the failure will still be 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.

[Related recommendations: mysql video tutorial]

The above is the detailed content of What is a trigger in mysql. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles