A trigger is a stored procedure - which is a set of SQL statements saved under a name, just like a function, so that it can be reused - that is executed automatically when a certain event occurs in a database.
For instance, you may program a trigger to execute when data is inserted in a table.
DML
(Database Manipulation Language) event is specified (INSERT
/UPDATE
/DELETE
)DDL
(Database Definition Language) event is specified (CREATE
/ALTER
)LOGON
/LOGOFF
/STARTUP
/SHUTDOWN
)
DML
)A trigger is implemented in the given code which will be fired before anything is inserted in the people
table. This trigger makes sure that a person does not have a negative age
and sets the age to zero.
CREATE TABLE people (age INT,name varchar(150));delimiter //CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age < 0 THEN SET NEW.age = 0; ENDIF; //INSERT INTO people VALUES (-20, 'Sid'), (30, 'Josh');select * from people;
Free Resources