mysql
  1. mysql-after-insert-trigger

After Insert Trigger - ( MySQL Triggers )

MySQL triggers are routines that are executed automatically when certain events occur in a table, such as when a row is inserted, updated, or deleted. In this tutorial, we'll focus on the after insert trigger, which is executed after a new row is inserted into a table.

Syntax

The basic syntax for creating an after insert trigger in MySQL is as follows:

CREATE TRIGGER trigger_name AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
    -- Trigger statements go here
END;

Here, "trigger_name" is the name of the trigger, "table_name" is the name of the table on which the trigger is defined, and "FOR EACH ROW" indicates that the trigger is executed for each row that is inserted into the table. The trigger statements go inside the BEGIN and END blocks.

Example

Let's say we have a table called "students" that stores the student name and grade for each student. We want to create a trigger that automatically inserts a new row into a separate "student_grades" table whenever a new student is added to the "students" table. Here's how we can implement the after insert trigger:

CREATE TRIGGER insert_student_grade
AFTER INSERT ON students
FOR EACH ROW
BEGIN
    INSERT INTO student_grades (student_name, grade) VALUES (NEW.name, NEW.grade);
END;

Here, "insert_student_grade" is the name of the trigger, "students" is the table on which the trigger is defined, and "NEW" refers to the newly inserted row in the "students" table. The trigger statement inside the BEGIN and END blocks inserts a new row into the "student_grades" table with the student's name and grade.

Explanation

In the example above, we created an after insert trigger called "insert_student_grade" that is executed automatically after a new row is inserted into the "students" table. The trigger inserts a new row into the "student_grades" table with the student's name and grade.

Use

After insert triggers can be used for a variety of scenarios, such as updating a separate table, sending a notification, or performing calculations based on the inserted data. They are useful for automating tasks and avoiding the need to manually perform actions after each insert.

Important Points

  • After insert triggers are executed automatically after a new row is inserted into a table.
  • The inserted row can be accessed using the "NEW" keyword.
  • After insert triggers can be used for a variety of scenarios, such as updating a separate table, sending a notification, or performing calculations based on the inserted data.

Summary

In this tutorial, we discussed how to create an after insert trigger in MySQL. We covered the syntax, example, explanation, use, and important points of after insert triggers. With this knowledge, you can now use after insert triggers in MySQL to automate tasks and avoid the need to manually perform actions after each insert.

Published on: