MySQL trigger to insert row into another table?


Let us first create a table. The CREATE command is used to create a table.

mysql> create table Table1
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.62 sec)

Let us now create another table.

mysql> create table Table2
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.49 sec)

Now, the following is how you can create a trigger.

mysql> delimiter #
mysql> create trigger Table1Trigger after insert on Table1
   -> for each row
   -> begin
   ->  insert into Table2(id, name) values (new.id, new.name);
   -> end#
Query OK, 0 rows affected (0.29 sec)

mysql> delimiter ;

To create a trigger, we need to change the delimiter.

Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1.

mysql> insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');
Query OK, 3 rows affected (0.28 sec)
Records: 3  Duplicates: 0  Warnings: 0

To check if the records are inserted in both tables or not.

mysql> select *from Table1;

Here is the output that shows record inserted successfully in Table1.

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)

To check for second table.

mysql>  select *from Table2;

The following is the output that shows record inserted successfully in Table2.

+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements