Trigger to insert data into table based on another table in same database

A trigger is a rule that you put on a table which basically says, whenever you DELETE, UPDATE or INSERT something in this table, also do something else. For instance, we might want to log a change, but instead of writing two separate queries, one for the change, and one for the log, we can instead write a trigger that says, "Whenever this row is updated, create a new row in a different table to tell me that the update was made". It adds a little overhead to the initial query, but since there are not two packets traveling to your database to do two separate things, there is an overall performance gain

CREATE TRIGGER nt AFTER INSERT ON t1 FOR EACH ROW INSERT INTO t2(idd, NAMES, ages) VALUES(new.id, new.name, new.age);

See Below Example :

CREATE DATABASE databasename;
USE databasename;
CREATE TABLE t1(id INT(10), NAME VARCHAR(30), age INT(10));
INSERT INTO t1 VALUES(001,'raju',20);
SELECT * FROM t1;
INSERT INTO t1 VALUES(002,'somi',29);
CREATE TABLE t2(idd INT(10), NAMES VARCHAR(30), ages INT(10));
DROP TRIGGER nt;
CREATE TRIGGER nt AFTER INSERT ON t1 FOR EACH ROW INSERT INTO t2(idd, NAMES, ages) VALUES(new.id, new.name, new.age);


Comments

Popular posts from this blog

Script For Login, Logout and View Using PHP, MySQL and Bootstrap

Real-Time Web Interface to MQTT using Socket.io and Node.js

Customize radio buttons and checkboxes with CSS sprites