INSERT Triggers
This lesson demonstrates how to create triggers that are associated with the INSERT statement.
We'll cover the following...
INSERT Triggers
The insert triggers are fired whenever an INSERT operation occurs. They can be executed before or after the insert query is executed. In the insert triggers, we can only use the NEW keyword to access the new values of a column. The OLD keyword cannot be used because there are no previous values for an INSERT statement. The BEFORE INSERT trigger can be used for data validation or for maintaining a summary table of another table. The AFTER INSERT trigger can be used for maintaining an activity log or to copy the values in a table to another table.
Syntax
CREATE TRIGGER trigger_name [BEFORE | AFTER] INSERT
ON table_name
FOR EACH ROW
trigger_body
Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy-paste the command ./DataJek/Lessons/47lesson.sh and wait for the mysql prompt to start-up.
-- The lesson queries are reproduced below for convenient copy/paste into the terminal.-- Query 1CREATE TABLE NetWorthStats (AverageNetWorth DECIMAL(10,4));INSERT INTO NetWorthStats(AverageNetWorth)Values ((SELECT AVG(NetWorthInMillions) FROM Actors));-- Query 2DELIMITER **CREATE TRIGGER BeforeActorsInsertBEFORE INSERT ON ActorsFOR EACH ROWBEGINDECLARE TotalWorth, RowsCount INT;SELECT SUM(NetWorthInMillions) INTO TotalWorthFROM Actors;SELECT COUNT(*) INTO RowsCountFROM Actors;UPDATE NetWorthStatsSET AverageNetWorth = ((Totalworth + new.NetWorthInMillions) / (RowsCount+1));END **DELIMITER ;-- Query 3INSERT INTO Actors (FirstName, SecondName, DoB, Gender, MaritalStatus, NetWorthInMillions)VALUES ('Charlize', 'Theron', '1975-08-07', 'Female', 'Single', 130);SELECT * FROM NetWorthStats;-- Query 4CREATE TABLE ActorsLog (LogId INT AUTO_INCREMENT PRIMARY KEY,ActorId INT NOT NULL,FirstName VARCHAR(20),LastName VARCHAR(20),DateTime DATETIME DEFAULT NULL,Event VARCHAR(50) DEFAULT NULL);-- Query 5CREATE TRIGGER AfterActorsInsertAFTER INSERT ON ActorsFOR EACH ROWINSERT INTO ActorsLogSET ActorId = NEW.Id,FirstName = New.FirstName,LastName = NEW.SecondName,DateTime = NOW(),Event = 'INSERT';-- Query 6INSERT INTO Actors (FirstName, SecondName, DoB, Gender, MaritalStatus, NetWorthInMillions)VALUES ('Matt', 'Damon', '1970-10-08', 'Male', 'Married', 160);SELECT * FROM ActorsLog;
-
We will first cover the BEFORE ...