MySQL Triggers
MySQL Triggers
Introduction on Triggers
A trigger is a set of actions that are run automatically when a specified change
operation (SQL INSERT, UPDATE, or DELETE statement) is performed on a
specified table. Triggers are useful for tasks such as enforcing business rules,
validating input data, and keeping an audit trail.
Uses for triggers:
MySQL Triggers
We assume that you are habituated with "MySQL Stored Procedures", if not you
can read our MySQL Procedures tutorial. You can use the following statements
of MySQL procedure in triggers:
Syntax:
CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
trigger_body
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
Explanation:
The trigger activates whenever a new row is inserted into the table; for example,
through INSERT, LOAD DATA, and REPLACE statements.
The trigger activates whenever a row is modified; for example, through UPDATE
statements.
The trigger activates whenever a row is deleted from the table; for example,
through DELETE and REPLACE statements. DROP TABLE and TRUNCATE
TABLE statements on the table do not activate this trigger, because they do not
use DELETE. Dropping a partition does not activate DELETE triggers, either.
tbl_name : The trigger becomes associated with the table named tbl_name,
which must refer to a permanent table. You cannot associate a trigger with a
TEMPORARY table or a view.
trigger_body: trigger_body is the statement to execute when the trigger
activates. To execute multiple statements, use the BEGIN ... END compound
statement construct. This also enables you to use the same statements that are
permissible within stored routines.
Here is a simple example:
mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account
-> FOR EACH ROW SET @sum = @sum + NEW.amount;
Query OK, 0 rows affected (0.06 sec)
In the above example, there is new keyword 'NEW' which is a MySQL extension
to triggers. There is two MySQL extension to triggers 'OLD' and 'NEW'. OLD and
NEW are not case sensitive.
Within the trigger body, the OLD and NEW keywords enable you to access
columns in the rows affected by a trigger
In an INSERT trigger, only NEW.col_name can be used.
In a UPDATE trigger, you can use OLD.col_name to refer to the columns of a
row before it is updated and NEW.col_name to refer to the columns of the row
after it is updated.
In a DELETE trigger, only OLD.col_name can be used; there is no new row.
A column named with OLD is read only. You can refer to it (if you have the
SELECT privilege), but not modify it. You can refer to a column named with NEW
if you have the SELECT privilege for it. In a BEFORE trigger, you can also
change its value with SET NEW.col_name = value if you have the UPDATE
privilege for it. This means you can use a trigger to modify the values to be
inserted into a new row or used to update a row. (Such a SET statement has no
effect in an AFTER trigger because the row change will have already occurred.)
Sample database, table, table structure, table records for various examples
Database Name: hr
Host Name : localhost
Database user : root
Password : ' '
You can write a procedure in MySQL command line tool or you can use MySQL
workbench which is an excellent front-end tool (here we have used version 5.3
CE).
After a successful login, you can access the MySQL command prompt:
Now you can write your own trigger on a specific table, see the following example
:
After successful login, a new screen will come and from the object browser
panel select a database:
After selecting the database, select the tables:
Now right click on emp_details a window pops up, click on Alter Table:
Clicking on " Alter Table " details of emp_details will come:
Now click on Trigger tab in the previous section, then select the Timing/Event it
may be AFTER DELETE, AFTER INSERT, AFTER UPDATE or BEFORE
DELETE, BEFORE INSERT OR BEFORE UPDATE. Let we select AFTER
INSERT, you also notice that there is a button Add Trigger.
Clicking on Add Trigger button a default code on trigger will come on the basis of
choosing Timing/Event:
Note: See a new text Delete Trigger has come in Add Trigger button. Clicking on
this you can delete the trigger.
Finally you can review the script once again, as there is no error, let click
on Apply button:
This the final window before finish. Let click on Finish button.
If you take a look at the schema, you will see emp_details_AINS trigger under
the emp_details table as follows:
We have a table student_marks with 10 columns and 4 rows. There are data only
in STUDENT_ID and NAME columns.
mysql> SELECT * FROM STUDENT_MARKS;
+------------+------------------+------+------+------+------+---
---+-------+-----------+-------+
| STUDENT_ID | NAME | SUB1 | SUB2 | SUB3 | SUB4 |
SUB5 | TOTAL | PER_MARKS | GRADE |
+------------+------------------+------+------+------+------+---
---+-------+-----------+-------+
| 1 | Steven King | 0 | 0 | 0 | 0 |
0 | 0 | 0.00 | |
| 2 | Neena Kochhar | 0 | 0 | 0 | 0 |
0 | 0 | 0.00 | |
| 3 | Lex De Haan | 0 | 0 | 0 | 0 |
0 | 0 | 0.00 | |
| 4 | Alexander Hunold | 0 | 0 | 0 | 0 |
0 | 0 | 0.00 | |
+------------+------------------+------+------+------+------+---
---+-------+-----------+-------+
4 rows in set (0.00 sec)
Now the exam is over and we have received all subject marks, now we will
update the table, total marks of all subject, the percentage of total marks and
grade will be automatically calculated. For this sample calculation, the following
conditions are assumed :
Total Marks (will be stored in TOTAL column) : TOTAL = SUB1 + SUB2 + SUB3
+ SUB4 + SUB5
Percentage of Marks (will be stored in PER_MARKS column) : PER_MARKS =
(TOTAL)/5