MySQL Stored Procedure and Triggers
MySQL Stored Procedure and Triggers
MySQL Stored Procedure and Triggers
If we consider the enterprise application, we always need to perform specific tasks such
as database cleanup, processing payroll, and many more on the database regularly.
Such tasks involve multiple SQL statements for executing each task. This process might
easy if we group these tasks into a single task. We can fulfill this requirement
in MySQL by creating a stored procedure in our database.
A procedure is called a recursive stored procedure when it calls itself. Most database
systems support recursive stored procedures. But, it is not supported well in MySQL.
Parameter Explanations
The procedure syntax has the following parameters:
parameter It represents the number of parameters. It can be one or more than one.
IN parameter
OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the stored
procedure, and the changed (new) value is passed back to the calling program. It is
noted that a procedure cannot access the OUT parameter's initial value when it starts.
INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the
argument, and the procedure can modify the INOUT parameter, and then passes the
new value back to the calling program.
Example
Let us understand how to create a procedure in MySQL through example. First, we need
to select a database that will store the newly created procedure. We can select the
database using the below statement:
Suppose this database has a table named student_info that contains the following data:
1. DELIMITER &&
2. CREATE PROCEDURE get_student (IN var1 INT)
3. BEGIN
4. SELECT * FROM student_info LIMIT var1;
5. SELECT COUNT(stud_code) AS Total_Student FROM student_info;
6. END &&
7. DELIMITER ;
1. DELIMITER &&
2. CREATE PROCEDURE display_max_mark (OUT highestmark INT)
3. BEGIN
4. SELECT MAX(marks) INTO highestmark FROM student_info;
5. END &&
6. DELIMITER ;
This procedure's parameter will get the highest marks from the student_info table.
When we call the procedure, the OUT parameter tells the database systems that its value
goes out from the procedures. Now, we will pass its value to a session variable @M in
the CALL statement as follows:
1. DELIMITER &&
2. CREATE PROCEDURE display_marks (INOUT var1 INT)
3. BEGIN
4. SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
5. END &&
6. DELIMITER ;
This statement displays all stored procedure names, including their characteristics.
If we want to display procedures in a particular database, we need to use
the WHERE clause. In case we want to list stored procedures with a specific word, we
need to use the LIKE clause.
We can list all stored procedure in the MySQL mystudentsb database using the below
statement:
It will give the below output where we can see that the mystudentdb database
contains four stored procedures:
How to delete/drop stored procedures in MySQL?
MySQL also allows a command to drop the procedure. When the procedure is dropped,
it is removed from the database server also. The following statement is used to drop a
stored procedure in MySQL:
We can verify it by listing the procedure in the specified database using the SHOW
PROCEDURE STATUS command. See the below output:
2. Right-click on the Stored Procedure, and we will get the default procedure code. See
the below screen:
3. Complete the procedure code and click on the Apply button. In the next window, we
will review the procedure code once again, and if no error was found, click on the Apply
button.
4. After clicking on the Apply button, click on the Finish button for completion.
5. We can navigate to the schema menu again to verify this newly created procedure. It
means first select your database and expand it to display its sub-menu. In the sub-
menu, expanding the stored procedure option will show the newly created procedure.
See the below image:
6. We can call the procedure by tapping on the red rectangle box or simply execute the
CALL statement.
The below statement is used to change the characteristics of a procedure but not
the actual procedure:
Suppose we want to add a comment to the existing procedure. In such a case, we can
use the ALTER statement as follows to accomplish this task:
After executing this statement, we can verify it by using the below statement:
It will display the below output where we can see that the comment is added
successfully.
It is to note that we can alter the body of the stored procedure in MySQL using the
workbench tool. So open this tool, navigate to the schema menu, and expand the
database that contains stored procedures. Now, select your procedure, right-click on it
and choose ALTER STORED PROCEDURE option. See the below screen:
After clicking this option, we will get a window that contains a procedure code. See the
below screen that contains procedure code to display all employee:
Now, we will modify this code. Suppose we want to display only male employees. To do
this, we can change this code from the below code and click on the Apply button:
o If we use stored procedures, the memory uses of every connection that uses
those stored procedures will increase substantially. Also, if we overuse many
logical applications inside stored procedures, the CPU usage will increase. It is
because the database server is not well designed for logical operations.
o Stored procedure's constructs are not designed to develop complex and flexible
business logic.
o It is difficult to debug stored procedures. Only a few database management
systems allow us to debug stored procedures. Unfortunately, MySQL does not
provide facilities for debugging stored procedures.
o It is not easy to develop and maintain stored procedures. Developing and
maintaining stored procedures are often required a specialized skill set that not
all application developers possess. It may lead to problems in both application
development and maintenance phases.
MySQL Trigger
A trigger in MySQL is a set of SQL statements that reside in a system catalog. It is a
special type of stored procedure that is invoked automatically in response to an
event. Each trigger is associated with a table, which is activated on any DML statement
such as INSERT, UPDATE, or DELETE.
A trigger is called a special procedure because it cannot be called directly like a stored
procedure. The main difference between the trigger and procedure is that a trigger is
called automatically when a data modification event is made against a table. In contrast,
a stored procedure must be called explicitly.
Generally, triggers are of two types according to the SQL standard: row-level triggers
and statement-level triggers.
Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs
on a table regardless of how many rows are inserted, updated, or deleted.
o MySQL triggers do not allow to use of all validations; they only provide extended
validations. For example, we can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY
constraints for simple validations.
o Triggers are invoked and executed invisibly from the client application. Therefore, it isn't
easy to troubleshoot what happens in the database layer.
o Triggers may increase the overhead of the database server.
1. Before Insert: It is activated before the insertion of data into the table.
2. After Insert: It is activated after the insertion of data into the table.
3. Before Update: It is activated before the update of data in the table.
4. After Update: It is activated after the update of the data in the table.
5. Before Delete: It is activated before the data is removed from the table.
6. After Delete: It is activated after the deletion of data from the table.
When we use a statement that does not use INSERT, UPDATE or DELETE query to
change the data in a table, the triggers associated with the trigger will not be invoked.
Naming Conventions
Naming conventions are the set of rules that we follow to give appropriate unique
names. It saves our time to keep the work organize and understandable. Therefore, we
must use a unique name for each trigger associated with a table. However, it is a
good practice to have the same trigger name defined for different tables.
The following naming convention should be used to name the trigger in MySQL:
Thus,
Parameter Explanation
The create trigger syntax contains the following parameters:
trigger_name: It is the name of the trigger that we want to create. It must be written
after the CREATE TRIGGER statement. It is to make sure that the trigger name should be
unique within the schema.
trigger_time: It is the trigger action time, which should be either BEFORE or AFTER. It is
the required parameter while defining a trigger. It indicates that the trigger will be
invoked before or after each row modification occurs on the table.
trigger_event: It is the type of operation name that activates the trigger. It can be
either INSERT, UPDATE, or DELETE operation. The trigger can invoke only one event at
one time. If we want to define a trigger which is invoked by multiple events, it is
required to define multiple triggers, and one for each event.
table_name: It is the name of the table to which the trigger is associated. It must be
written after the ON keyword. If we did not specify the table name, a trigger would not
exist.
BEGIN END Block: Finally, we will specify the statement for execution when the trigger
is activated. If we want to execute multiple statements, we will use the BEGIN END block
that contains a set of queries to define the logic for the trigger.
The trigger body can access the column's values, which are affected by the DML
statement. The NEW and OLD modifiers are used to distinguish the column
values BEFORE and AFTER the execution of the DML statement. We can use the column
name with NEW and OLD modifiers as OLD.col_name and NEW.col_name. The
OLD.column_name indicates the column of an existing row before the updation or
deletion occurs. NEW.col_name indicates the column of a new row that will be inserted
or an existing row after it is updated.
For example, suppose we want to update the column name message_info using the
trigger. In the trigger body, we can access the column value before the update
as OLD.message_info and the new value NEW.message_info.
We can understand the availability of OLD and NEW modifiers with the below table:
INSERT No Yes
ELETE Yes No
Next, execute the below statement to fill the records into the employee table:
1. INSERT INTO employee VALUES
2. ('Robin', 'Scientist', '2020-10-04', 12),
3. ('Warner', 'Engineer', '2020-10-04', 10),
4. ('Peter', 'Actor', '2020-10-04', 13),
5. ('Marco', 'Doctor', '2020-10-04', 14),
6. ('Brayden', 'Teacher', '2020-10-04', 12),
7. ('Antonio', 'Business', '2020-10-04', 11);
Next, we will create a BEFORE INSERT trigger. This trigger is invoked automatically
insert the working_hours = 0 if someone tries to insert working_hours < 0.
1. mysql> DELIMITER //
2. mysql> Create Trigger before_insert_empworkinghours
3. BEFORE INSERT ON employee FOR EACH ROW
4. BEGIN
5. IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
6. END IF;
7. END //
After execution of the above statement, we will get the output as follows:
In this output, we can see that on inserting the negative values into the working_hours
column of the table will automatically fill the zero value by a trigger.
The following steps are necessary to get the list of all triggers:
Step 1: Open the MySQL Command prompt and logged into the database server using
the password that you have created during MySQL's installation. After a successful
connection, we can execute all the SQL statements.
Step 2: Next, choose the specific database by using the command below:
Play Video
x
Let us understand it with the example given below. Suppose we have a database
name "mysqltestdb" that contains many tables. Then execute the below statement to
list the triggers:
When we execute the above statements, we will get the same result.
Example
Suppose we want to show all triggers that belongs to the employee table, execute the
statement as follows:
NOTE: It is to note that we must have a SUPER privilege to execute the SHOW
TRIGGERS statement.
The show trigger statement contains several columns in the result set. Let us explain
each column in detail.
o Trigger: It is the name of the trigger that we want to create and must be unique within
the schema.
o Event: It is the type of operation name that invokes the trigger. It can be either INSERT,
UPDATE, or DELETE operation.
o Table: It is the name of the table to which the trigger belongs.
o Statement: It is the body of the trigger that contains logic for the trigger when it
activates.
o Timing: It is the activation time of the trigger, either BEFORE or AFTER. It indicates that
the trigger will be invoked before or after each row of modifications occurs on the table.
o Created: It represents the time and date when the trigger is created.
o sql_mode: It displays the SQL_MODE when the trigger is executed.
o Definer: It is the name of a user account that created the trigger and should be in the
'user_name'@'host_name' format.
o character_set_client: It was the session value of the character_set_client system variable
when the trigger was created.
o collation_connection: It was the session value of the character_set_client system
variable when the trigger was created.
o Database Collation: It determines the rules that compare and order the character string.
It is the collation of the database with which the trigger belongs.
1. Go to the Navigation tab and click on the Schema menu that contains all the
databases available in the MySQL server.
2. Select the database (for example, mysqltestdb), double click on it, and show the sub-
menu containing Tables, Views, Functions, and Stored Procedures. See the below
screen.
3. Click on the Tables sub-menu and select the table on which you have created a
trigger. See the below image:
4. Clicking on the Triggers sub-menu, we can see all triggers associated with the
selected table. See the below image.
MySQL DROP Trigger
We can drop/delete/remove a trigger in MySQL using the DROP TRIGGER statement. You
must be very careful while removing a trigger from the table. Because once we have deleted the
trigger, it cannot be recovered. If a trigger is not found, the DROP TRIGGER statement throws
an error.
Parameter Explanation
The parameters used in the drop trigger syntax are explained as follows:
Parameter Descriptions
Trigger_name It is the name of a trigger that we want to remove from the database server. It is a require
parameter.
Schema_nam It is the database name to which the trigger belongs. If we skip this parameter, the statemen
e will remove the trigger from the current database.
IF_EXISTS It is an optional parameter that conditionally removes triggers only if they exist on th
database server.
If we remove the trigger that does not exist, we will get an error. However, if we have specified
the IF EXISTS clause, MySQL gives a NOTE instead of an error.
It is to note that we must have TRIGGER privileges before executing the DROP TRIGGER
statement for the table associated with the trigger. Also, removing a table will automatically
delete all triggers associated with the table.
After executing the statement, we can see that there are two triggers
named before_update_salaries and sales_info_before_update. See the below image:
It will successfully delete a trigger from the database. If we execute the above statement again, it
will return an error message. See the output:
If we execute the above statement again with an IF EXISTS clause, it will return the warning
message instead of producing an error. See the output:
1. Go to the Navigation tab and click on the Schema menu. It will display all databases
available in the MySQL database server.
2. Select the database (for example, mystudentdb). Then, double click on the selected schema.
It displays the sub-menu containing Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select a table on which a trigger is associated. Again expand
the selected Table -> Triggers; we will get the below image:
4. Now, right-click on the selected table and choose the Alter Table option that gives the screen
as below:
5. Now, click on the Trigger tab shown in the previous section's red rectangular box. You
will notice that there is a (+) and (-) icon button to add or delete a trigger:
6. Now, clicking on the (-) button will permanently remove the trigger associated with
the table.
MySQL BEFORE INSERT TRIGGER
Before Insert Trigger in MySQL is invoked automatically whenever an insert operation is
executed. In this article, we are going to learn how to create a before insert trigger with
its syntax and example.
Syntax
The following is the syntax to create a BEFORE INSERT trigger in MySQL:
o First, we will specify the name of the trigger that we want to create. It should be
unique within the schema.
o Second, we will specify the trigger action time, which should be BEFORE INSERT.
This trigger will be invoked before each row modifications occur on the table.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the statement for execution when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that
contains a set of queries to define the logic for the trigger. See the below syntax:
x
1. DELIMITER $$
2. CREATE TRIGGER trigger_name BEFORE INSERT
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
o We can access and change the NEW values only in a BEFORE INSERT trigger.
o We cannot access the OLD If we try to access the OLD values, we will get an error
because OLD values do not exist.
o We cannot create a BEFORE INSERT trigger on a VIEW.
Next, we will insert some records into the employee table and then execute the SELECT
statement to see the table data as follows:
Next, we will use a CREATE TRIGGER statement to create a BEFORE INSERT trigger. This
trigger is invoked automatically that inserts the occupation = 'Leader' if someone tries
to insert the occupation = 'Scientist'.
1. mysql> DELIMITER //
2. mysql> Create Trigger before_insert_occupation
3. BEFORE INSERT ON employee FOR EACH ROW
4. BEGIN
5. IF NEW.occupation = 'Scientist' THEN SET NEW.occupation = 'Doctor';
6. END IF;
7. END //
After execution of the above statement, we will get the output as follows:
Execute the SELECT statement to verify the output:
In this output, we can see that on inserting the occupation column values as 'Scientist',
the table will automatically fill the 'Doctor' value by invoking a trigger.
1. Go to the Navigation tab and click on the Schema menu that contains all the
databases available in the MySQL server.
2. Select the database (for example, mysqltestdb), double click on it. It will show
the sub-menu containing Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select the table on which you want to create a
trigger. After selecting a table, right-click on the selected table (for example, employee),
and then click on the Alter Table option. See the below image:
Syntax
The following is the syntax to create an AFTER INSERT trigger in MySQL:
o First, we will specify the name of the trigger that we want to create. It should be
unique within the schema.
o Second, we will specify the trigger action time, which should be AFTER INSERT
clause to invoke the trigger.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the trigger body that contains one or more statements for
execution when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that
contains a set of SQL queries to define the logic for the trigger. See the below syntax:
1. DELIMITER $$
2. CREATE TRIGGER trigger_name AFTER INSERT
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
o We can access the NEW values but cannot change them in an AFTER INSERT
trigger.
o We cannot access the OLD If we try to access the OLD values, we will get an error
because there is no OLD on the INSERT trigger.
o We cannot create the AFTER INSERT trigger on a VIEW.
Next, we will insert some records into this table and then execute the SELECT
statement to see the table data as follows:
Again, we will create a new table named "student_detail" as follows:
1. mysql> DELIMITER //
2. mysql> Create Trigger after_insert_details
3. AFTER INSERT ON student_info FOR EACH ROW
4. BEGIN
5. INSERT INTO student_detail VALUES (new.stud_id, new.stud_code,
6. new.stud_name, new.subject, new.marks, new.phone, CURTIME());
7. END //
If the trigger is created successfully, we will get the output as follows:
The table that has been modified after the update query executes is student_detail. We
can verify it by using the SELECT statement as follows:
In this output, we can see that on inserting values into the student_info table, the
student_detail table will automatically fill the records by invoking a trigger.
1. Go to the Navigation tab and click on the Schema menu that contains all the
databases available in the MySQL server.
2. Select the database (for example, mystudentdb), double click on it that shows
the sub-menu containing Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select the table on which you want to create a
trigger. After selecting a table, right-click on the selected table (for example,
mystudentdb), and then click on the Alter Table option. See the below image:
6. Now, complete the trigger code, review them once again, and if no error is found,
click on the Apply button.
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we look at the schema menu, we can see AFTER_INSERT_detail trigger under
the student_info table as follows:
Syntax
The following is the syntax to create a BEFORE UPDATE trigger in MySQL:
o First, we will specify the trigger name that we want to create. It should be unique
within the schema.
o Second, we will specify the trigger action time, which should be BEFORE
UPDATE. This trigger will be invoked before each row of alterations occurs on the
table.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the trigger body that contains a statement for execution
when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that
contains a set of queries to define the logic for the trigger. See the below syntax:
1. DELIMITER $$
2. CREATE TRIGGER trigger_name BEFORE UPDATE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
Next, we will insert some records into the sales_info table as follows:
Then, execute the SELECT statement to see the table data as follows:
Next, we will use a CREATE TRIGGER statement to create a BEFORE UPDATE trigger.
This trigger is invoked automatically before an update event occurs in the table.
1. DELIMITER $$
2.
3. CREATE TRIGGER before_update_salesInfo
4. BEFORE UPDATE
5. ON sales_info FOR EACH ROW
6. BEGIN
7. DECLARE error_msg VARCHAR(255);
8. SET error_msg = ('The new quantity cannot be greater than 2 times the current quanti
ty');
9. IF new.quantity > old.quantity * 2 THEN
10. SIGNAL SQLSTATE '45000'
11. SET MESSAGE_TEXT = error_msg;
12. END IF;
13. END $$
14.
15. DELIMITER ;
This statement works well because it does not violate the rule. Next, we will execute the
below statements that update the quantity of the row as 600 whose id = 2
It will give the error as follows because it violates the rule. See the below output.
How to create BEFORE UPDATE Trigger in MySQL
workbench?
To create a BEFORE UPDATE trigger using MySQL workbench, we first need to launch it
and then log in using the username and password we created earlier. We will get the
screen as follows:
2. Select the database (for example, employeedb), double click on it, and display
the sub-menu containing Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select the table on which you want to create a
trigger. After selecting a table, right-click on the selected table (for example, sales_info),
and then click on the Alter Table option. See the below image:
4. Clicking on the Alter Table option gives the screen as below:
5. Now, click on the Trigger tab shown in the previous section's red rectangular box,
then select the Timing/Event BEFORE UPDATE. We will notice that there is a (+) icon
button to add a trigger. Clicking on that button, we will get a default code on trigger
based on choosing Timing/Event:
6. Now, complete the trigger code, review them once again, and if no error is found,
click on the Apply button.
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we take at the schema menu, we will see
the trigger sales_info_before_update under the sales_info table as follows:
MySQL AFTER UPDATE TRIGGER
The AFTER UPDATE trigger in MySQL is invoked automatically whenever an UPDATE
event is fired on the table associated with the triggers. In this article, we are going to
learn how to create an AFTER UPDATE trigger with its syntax and example.
Syntax
The following is the syntax to create an AFTER UPDATE trigger in MySQL:
o First, we will specify the trigger name that we want to create. It should be unique
within the schema.
o Second, we will specify the trigger action time, which should be AFTER UPDATE.
This trigger will be invoked after each row of alterations occurs on the table.
o Third, we will specify the table name to which the trigger is associated. It must
be written after the ON If we did not specify the table name, a trigger would not
exist.
o Finally, we will specify the trigger body that contains a statement for execution
when the trigger is activated.
If we want to execute more than one statement, we will use the BEGIN END block that
contains a set of SQL queries to define the logic for the trigger. See the below syntax:
1. DELIMITER $$
2. CREATE TRIGGER trigger_name AFTER UPDATE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
Suppose we have created a table named students to store the student's information as
follows:
Next, we will insert some records into this table using the below statement:
We will then create an AFTER UPDATE trigger that promotes all students in the next
class, i.e., 6 will be 7, 7 will be 8, and so on. Whenever an updation is performed on a
single row in the "students" table, a new row will be inserted in the "students_log"
table. This table keeps the current user id and a description regarding the current
update. See the below trigger code.
1. DELIMITER $$
2.
3. CREATE TRIGGER after_update_studentsInfo
4. AFTER UPDATE
5. ON students FOR EACH ROW
6. BEGIN
7. INSERT into students_log VALUES (user(),
8. CONCAT('Update Student Record ', OLD.name, ' Previous Class :',
9. OLD.class, ' Present Class ', NEW.class));
10. END $$
11.
12. DELIMITER ;
In this trigger, we have first specified the trigger name after_update_studentsInfo.
Then, specify the triggering event. Third, we have specified the table name on which the
trigger is associated. Finally, we have written the trigger logic inside the trigger body
that performs updation in the "students" table and keeps the log information in the
"students_log" table.
Next, we will query data from the students and students_log table. We can see that
table has been updated after the execution of the query. See the below output:
Again, we will query data from the students_log table that keeps the current user id and
a description regarding the current update. See the below output:
1. Go to the Navigation tab and click on the Schema menu. It will display all databases
available in the MySQL database server.
2. Select the database (for example, mystudentdb). Then, double click on the selected
schema. It displays the sub-menu containing Tables, Views, Functions, and Stored
Procedures. See the below screen.
3. Expand the Tables sub-menu and select a table on which you want to create a trigger.
Then, right-click on the selected table (for example, students), and click on the Alter
Table option. See the below image:
4. Clicking on the Alter Table option gives the screen as below:
5. Now, click on the Trigger tab shown in the previous section's red rectangular box,
then select the Timing/Event AFTER UPDATE. We will notice that there is a (+) icon
button to add a trigger. Clicking on that button, we will get a default code on the
trigger based on choosing Timing/Event:
6. Now, complete the trigger code, review them once again, and if no error is found,
click on the Apply button.
7. After clicking on the Apply button, click on the Finish button to complete the
process.
8. If we look at the schema menu, we can see student_update_trigger under the
"students" table as follows:
MySQL BEFORE DELETE Trigger
BEFORE DELETE Trigger in MySQL is invoked automatically whenever a delete operation
is fired on the table. In this article, we are going to learn how to create a before delete
trigger with its syntax and example.
Syntax
The following is the syntax to create a BEFORE DELETE trigger in MySQL:
o First, we will specify the name of the trigger that we want to create. It should be
unique within the schema.
o Second, we will specify the trigger action time, which should be BEFORE DELETE.
This trigger will be invoked before each row of alterations occurs on the table.
o Third, we will specify the name of a table to which the trigger is associated. It
must be written after the ON keyword. If we did not specify the table name, a
trigger would not exist.
o Finally, we will specify the statement for execution when the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that
contains a set of queries to define the logic for the trigger. See the below syntax:
49.3M
905
HTML Tutorial
1. DELIMITER $$
2. CREATE TRIGGER trigger_name BEFORE DELETE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
o We can access the OLD rows but cannot update them in a BEFORE DELETE
trigger.
o We cannot access the NEW rows. It is because there are no new row exists.
o We cannot create a BEFORE DELETE trigger on a VIEW.
Suppose we have created a table named salaries to store the salary information of an
employee as follows:
Next, we will insert some records into this table using the below statement:
We will then create a BEFORE DELETE trigger that inserts a new record into the
salary_archives table before a row is deleted from the salaries table.
1. DELIMITER $$
2.
3. CREATE TRIGGER before_delete_salaries
4. BEFORE DELETE
5. ON salaries FOR EACH ROW
6. BEGIN
7. INSERT INTO salary_archives (emp_num, valid_from, amount)
8. VALUES(OLD. emp_num, OLD.valid_from, OLD.amount);
9. END$$
10.
11. DELIMITER ;
In this trigger, we have first specified the trigger name before_delete_salaries. Then,
specify the triggering event. Third, we have specified the table name on which the
trigger is associated. Finally, we have written the trigger logic inside the trigger body
that insert the deleted row into the salary_archives table.
Second, we will query data from the salary_archives table to verify the above-created
trigger is invoked or not by using the select statement:
After executing a statement, we can see that the trigger was invoked successfully and
inserted a new record into the salary_archives table.
Third, we will remove all rows from the salaries table:
Finally, we will query data from the salary_archives table again. The trigger was called
four times because the DELETE statement removed four records from the salaries table.
See the below output:
1. Go to the Navigation tab and click on the Schema menu that contains all the
databases available in the MySQL server.
2. Select the database (for example, employeedb), double click on it. It will show
the sub-menu that contains Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select the table on which you want to create
a trigger. After selecting a table, right-click on the selected table (for example, salaries),
and then click on the Alter Table option. See the below image:
4. Clicking on the Alter Table option gives the screen as below:
5. Now, click on the Trigger tab shown in the red rectangular box of the previous
section, then select the Timing/Event BEFORE DELETE. We will notice that there is a (+)
icon button to add a trigger. Clicking on that button, we will get a default code on
trigger based on choosing Timing/Event:
6. Now, complete the trigger code, review them once again, and if no error is found,
click on the Apply button.
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we take at the schema menu, we will see the trigger salaries_before_trigger under
the salaries table as follows:
Syntax
The following is the syntax to create an AFTER DELETE trigger in MySQL:
If we want to execute multiple statements, we will use the BEGIN END block that
contains a set of SQL queries to define the logic for the trigger. See the below syntax:
58.1M
1.1K
C++ vs Java
1. DELIMITER $$
2. CREATE TRIGGER trigger_name AFTER DELETE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
Restrictions
o We can access the OLD rows but cannot update them in the AFTER DELETE
trigger.
o We cannot access the NEW rows. It is because there are no NEW row exists.
o We cannot create an AFTER DELETE trigger on a VIEW.
Next, we will insert some records into this table using the below statement:
Third, we will create another table named total_salary_budget that keeps the salary
information from the salaries table.
We will then create an AFTER DELETE trigger that updates the total salary into the
total_salary_budget table after a row is deleted from the salaries table.
1. DELIMITER $$
2.
3. CREATE TRIGGER after_delete_salaries
4. AFTER DELETE
5. ON salaries FOR EACH ROW
6. BEGIN
7. UPDATE total_salary_budget SET total_budget = total_budget - old.amount;
8. END$$
9.
10. DELIMITER ;
In this trigger, we have first specified the trigger name after_delete_salaries. Then,
specify the triggering event. Third, we have specified the table name on which the
trigger is associated. Finally, we have written the trigger logic inside the trigger body
that updates the total salary into the total_salary_budget table after a row is deleted
from the salaries table.
Next, we will query data from the total_salary_budget table. We can see that table has
been modified after the execution of the query. See the below output:
Again, we will query data from the total_salary_budget table. We can see that the trigger
updated the table to zero after the execution of the query. See the below output:
1. Go to the Navigation tab and click on the Schema menu that contains all the
databases available in the MySQL server.
2. Select the database (for example, employeedb), double click on it that shows
the sub-menu containing Tables, Views, Functions, and Stored Procedures. See the
below screen.
3. Expand the Tables sub-menu and select the table on which you want to create a
trigger. After selecting a table, right-click on the selected table (for example, salaries),
and then click on the Alter Table option. See the below image:
4. Clicking on the Alter Table option gives the screen as below:
5. Now, click on the Trigger tab shown in the previous section's red rectangular box,
then select the Timing/Event AFTER DELETE. We will notice that there is a (+) icon
button to add a trigger. Clicking on that button, we will get a default code on the trigger
based on choosing Timing/Event:
6. Now, complete the trigger code, review them once again, and if no error is found,
click on the Apply button.
7. After clicking on the Apply button, click on the Finish button for completion.
8. If we look at the schema menu, we can see salaries_AFTER_DELETE trigger under
the salaries table as follows: