...

/

INSERT Triggers

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.

Press + to interact
-- The lesson queries are reproduced below for convenient copy/paste into the terminal.
-- Query 1
CREATE TABLE NetWorthStats (
AverageNetWorth DECIMAL(10,4)
);
INSERT INTO NetWorthStats(AverageNetWorth)
Values ((SELECT AVG(NetWorthInMillions) FROM Actors));
-- Query 2
DELIMITER **
CREATE TRIGGER BeforeActorsInsert
BEFORE INSERT ON Actors
FOR EACH ROW
BEGIN
DECLARE TotalWorth, RowsCount INT;
SELECT SUM(NetWorthInMillions) INTO TotalWorth
FROM Actors;
SELECT COUNT(*) INTO RowsCount
FROM Actors;
UPDATE NetWorthStats
SET AverageNetWorth = ((Totalworth + new.NetWorthInMillions) / (RowsCount+1));
END **
DELIMITER ;
-- Query 3
INSERT INTO Actors (FirstName, SecondName, DoB, Gender, MaritalStatus, NetWorthInMillions)
VALUES ('Charlize', 'Theron', '1975-08-07', 'Female', 'Single', 130);
SELECT * FROM NetWorthStats;
-- Query 4
CREATE 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 5
CREATE TRIGGER AfterActorsInsert
AFTER INSERT ON Actors
FOR EACH ROW
INSERT INTO ActorsLog
SET ActorId = NEW.Id,
FirstName = New.FirstName,
LastName = NEW.SecondName,
DateTime = NOW(),
Event = 'INSERT';
-- Query 6
INSERT INTO Actors (FirstName, SecondName, DoB, Gender, MaritalStatus, NetWorthInMillions)
VALUES ('Matt', 'Damon', '1970-10-08', 'Male', 'Married', 160);
SELECT * FROM ActorsLog;
Terminal 1
Terminal
Loading...
  1. We will first cover the BEFORE ...