Trigger in MySQL


In the MySQL Trigger After Insert  command, records in a table the trigger after we have perform an insert a records or rows to the table.

Example : First of all we have to create a table 'Emp_info. This table is used to construct a table 'Emp_info.

Create table:-

CREATE TABLE Emp_info(
id int(6),
first_name VARCHAR(20),
last_name VARCHAR(15),
start_date DATE,
end_date DATE,
city VARCHAR(10),
description VARCHAR(15)
);

Insert data into table:-

Insert into add the records or rows into a table Emp_info.

insert into Emp_info values (01,'Akash','Ahlawat','20081225','20100625','Muzaffarnagar','Developer');

insert into Emp_info values (02,'Parshant','Choudhry','20071122','20100421','Faridabad','Human Resource');


insert into Emp_info values (03,'Arjun','Singh','20061012','20070512','Shamli','Developer');


View table:-
To view a table Emp_infowe use select query that return the records from a table 'Emp_info'.
mysql> select * from emp_info;

Output:-

ap-1.gif

Create table:-

The create table construct a table Emp_log.

CREATE TABLE Emp_log(
id int,
first_name varchar(50),
last_name varchar(50),
start_date date,
end_date date,
city varchar(50),
description varchar(50),
Lasinserted Time
);

View table:-

mysql  select * from emp_log;

Output:-

ap-2.gif

 

Create Trigger:-

The Create Trigger create a trigger 'Emp_info_Trigger' on table 'Emp_info'. The 'After insert trigger'  fired the trigger after you performed a insert operation on a table.

mysql> delimiter $$
CREATE TRIGGER Emp_info_Trigger
AFTER insert ON Emp_info
FOR EACH ROW
BEGIN
insert into Emp_log values(new.id,new.first_name,
new.last_name,new.start_date,new.end_date,
new.city,new.description,curtime());
    
mysql> delimiter ;

ap-3.gif

Query to insert into emp_info table:-

The insert into add the records or rows into the table 'emp_info'.

mysql> insert into emp_info values (4,'Amit','Kumar','20081225','20101203','Lucknow','Programmer');

Table that has been modified after update query executes is Emp_log:-

Query to view Emp_log table:-

mysql> select * from emp_log;

Output:-

ap-4.gif

Up Next
    Ebook Download
    View all
    Learn
    View all