๐ Comprehensive Notes: MySQL Triggers
1. What is a MySQL Trigger?
A trigger is a stored program (a block of code) that executes automatically
when a specific event happens to a table in your database. You do not
have to manually call a trigger like you do a Stored Procedure; the
database does it for you.
2. When do they happen?
Triggers are "set off" by three main data events:
โโ INSERT: When new data is added.
โโ UPDATE: When existing data is changed.
โโ DELETE: When data is removed.
3. Why use them? (Benefits)
โโ Automation: They remove the need to rewrite code. If you need a
specific action to happen every time data changes, you write it once
in a trigger, and it runs automatically forever.
โโ Audit Trails: They are excellent for security and logging. You can
create a trigger that keeps a log record every time someone changes
sensitive data.
โโ Data Integrity: They act as an alternative to constraints,
double-checking data to ensure it follows the rules before or after it is
saved.
4. Real-World Example: Lucky Shrub
The transcript describes a scenario for a company called "Lucky Shrub":
โโ The Problem: The sales team is adding discounts. If a discount is
greater than 25%, a manager must review it.
โโ The Solution: Instead of trusting employees to report themselves, a
trigger is added to the database.
โโ The Logic: The trigger is set to AFTER UPDATE. As soon as an item
is updated with a high discount, the trigger automatically flags it for an
"Approval Request".
5. How to Create a Trigger
To build a trigger, you use the CREATE TRIGGER statement. You must
define:
1.โ Unique Name: Give it a custom name (e.g., approval_request).
2.โ Timing & Event: Decide if it runs BEFORE or AFTER the event, and
if the event is an INSERT, UPDATE, or DELETE.
3.โ Table: Link it to a specific table.
4.โ The Logic: Write the code that should run. If it is more than one line
of code, you must wrap it inside BEGIN and END blocks.
6. How to Delete a Trigger
If you no longer need a trigger, you remove it using the DROP TRIGGER
command.
โโ Safety First: Use the IF EXISTS clause. This prevents an error if
the trigger is already gone (e.g., DROP TRIGGER IF EXISTS
schema_name.trigger_name).
โโ Automatic Deletion: If you delete (DROP) a table, MySQL
automatically deletes all triggers attached to that table.
๐ถ The "5-Year-Old" Version
Imagine you have a Cookie Jar (The Database Table).
A Trigger is like a Magic Robot that lives on top of the cookie jar. You don't
have to talk to the robot. You don't even have to know the robot is there.
โก
But, if you try to take a cookie (DELETE) or put a cookie in (INSERT)...
ZAP!
The robot wakes up automatically and does a job.
โโ Maybe the robot rings a bell (Sends an alert).
โโ Maybe the robot writes your name on a list "Timmy took a cookie at 3
PM" (Audit Log).
You play with the cookies, and the robot handles the rules automatically!
โ๏ธ Practice Exercise
Scenario: You are the database engineer for a bank. You want to make
sure no one deletes a customer account without a record being kept.
Task: Create a trigger called LogAccountDeletion.
โโ Timing: It should happen AFTER a row is DELETED from the
Accounts table.
โโ Action: It should INSERT the AccountID and the DeletionDate
into a table called DeletedLog.
Solution Code:
DELIMITER //
CREATE TRIGGER LogAccountDeletion
AFTER DELETE
ON Accounts FOR EACH ROW
BEGIN
-- This happens automatically when an account is deleted
INSERT INTO DeletedLog (AccountID, DeletionDate)
VALUES (OLD.AccountID, NOW());
END //
DELIMITER ;
๐ Comprehensive Notes: Types of MySQL Triggers
1. The Two Main Categories
There are two theoretical ways triggers can work in SQL, though MySQL
only supports one of them.
โโ Row-Level Triggers:
โโ Definition: This trigger activates for every single row that is
inserted, updated, or deleted.
โโ Example: If you run one statement that inserts 100 rows, the
trigger will fire 100 times (once for each row).
โโ Important Note: MySQL only supports Row-Level triggers.
โโ Statement-Level Triggers:
โโ Definition: This trigger activates only once for the entire SQL
action, regardless of how many rows are affected.
โโ Example: If you insert 100 rows with a single command, the
trigger fires only 1 time.
2. Timing: "Before" vs. "After"
You can control when the trigger runs relative to the database action.
โโ BEFORE Triggers:
โโ The trigger runs before the change is actually made to the
database.
โโ Best Use: validating data or fixing bad data (constraints) before
it gets saved.
โโ Example: Checking if a number is negative before saving it.
โโ AFTER Triggers:
โโ The trigger runs after the action is successfully performed.
โโ Best Use: Logging, auditing, or notifying other tables that a
change happened.
โโ Example: Sending a record to an archive table after a row is
deleted.
3. The 6 Possible Combinations
By combining the timing (BEFORE/AFTER) with the events
(INSERT/UPDATE/DELETE), you get these standard trigger types:
Timing
Event
Description
BEFORE
INSERT
Runs before a new row is added.
AFTER
INSERT
Runs after a new row is added.
BEFORE
UPDATE Runs before an existing row is changed.
AFTER
UPDATE Runs after an existing row is changed.
BEFORE
DELETE Runs before a row is removed.
AFTER
DELETE Runs after a row is removed.
4. Real-World Examples (Lucky Shrub Case Study)
The transcript provides three specific scenarios used by the company
"Lucky Shrub":
1.โ The Negative Number Fix (BEFORE INSERT)
โโ Goal: Ensure no negative numbers are entered into the
OrderQuantity field.
โโ Solution: Use a BEFORE INSERT trigger. If the logic sees a
number less than 0, it automatically changes it to 0 before
saving.
2.โ The New Order Log (AFTER INSERT)
โโ Goal: Keep an audit trail of every new order.
โโ Solution: Use an AFTER INSERT trigger to send a message to
an Audits table every time a new order is successfully added.
3.โ The Deletion Log (AFTER DELETE)
โโ Goal: Record the exact date and time an order was removed.
โโ Solution: Use an AFTER DELETE trigger to capture the
timestamp when a record is deleted.
๐ถ The "5-Year-Old" Version
Imagine you are drawing a picture.
1. The "BEFORE" Trigger (The Teacher)
โโ Before you are allowed to put your drawing on the wall, the teacher
looks at it.
โโ If you used a bad word, she erases it before it goes up.
โโ This is like the "Before Insert" trigger fixing negative numbers.
2. The "AFTER" Trigger (The Camera)
โโ You put your drawing on the wall. You are done.
โโ After it is up, your mom takes a photo of it for her scrapbook.
โโ She can't change the drawing; she just records that you did it.
โโ This is like the "After Insert" trigger saving a log.
3. Row-Level (The Sticker)
โโ If you draw 100 pictures, the teacher has to check every single one
(100 checks).
โโ MySQL is like this teacher—it checks every single row, one by one.
โ๏ธ Practice Exercise
Scenario: Based on the "Negative Number Fix" described in the notes. You
have a table Products with a column StockLevel. You want to make
sure no one accidentally sets the stock level to a negative number.
Task: Complete the code below to create a trigger that checks if
StockLevel is less than 0. If it is, force it to be 0.
Fill in the blanks:
DELIMITER //
CREATE TRIGGER ValidateStock
_______ INSERT -- (Hint: Should this happen BEFORE or AFTER we
save?)
ON Products
FOR EACH _______ -- (Hint: Does this happen for the whole group or one
by one?)
BEGIN
IF NEW.StockLevel < 0 THEN
SET NEW.StockLevel = 0;
END IF;
END //
DELIMITER ;
Answers to the blanks:
1.โ BEFORE: You must catch the mistake before it is saved.
2.โ ROW: MySQL triggers must apply "FOR EACH ROW".
๐ Comprehensive Notes: Creating and Dropping Triggers
1. The Goal (Lucky Shrub Scenario)
In the example provided, the company Lucky Shrub has a specific problem:
they want to ensure that no negative numbers (minus values) are entered
into the "Quantity" column of their orders.
โโ The Rule: If a user tries to enter a negative number, the system
should automatically change it to zero.
โโ The Tool: A BEFORE INSERT trigger is used because we need to
catch the data before it is saved.
2. Anatomy of Creating a Trigger
To build this, you use the CREATE TRIGGER command. Here is the
step-by-step breakdown of the syntax:
โโ Step 1: Unique Name
โโ You must give the trigger a name that does not exist elsewhere
in the database, such as OrderQuantityCheck.
โโ Step 2: Timing and Event
โโ You specify BEFORE INSERT. This tells MySQL to run this
code immediately before a new row is added.
โโ Step 3: Target Table
โโ Use the ON keyword followed by the table name (e.g., ON
Orders).
โโ Step 4: Scope
โโ Use FOR EACH ROW. This ensures the trigger checks every
single item being added, not just the whole batch at once.
โโ Step 5: The Logic (The Body)
โโ This is where you write the SQL code (IF statements) to check
the data.
โโ If you have more than one line of logic, you must wrap it in a
BEGIN and END block.
3. Understanding NEW vs OLD Modifiers
Inside the trigger logic, you need to look at the data coming in. MySQL
provides two special keywords for this:
โโ NEW: Represents the value that is about to be inserted or updated
(the future value).
โโ Usage: In this lesson, we use IF NEW.Quantity < 0 to
check the incoming number.
โโ OLD: Represents the value that already exists in the table before the
change (the past value).
4. Execution Steps
Because triggers use semicolons ; inside their logic, you must temporarily
change the delimiter (the symbol that ends a command) before creating
one.
1.โ Change Delimiter: DELIMITER //
2.โ Run Trigger Code: (The CREATE TRIGGER block)
3.โ Reset Delimiter: DELIMITER ;
5. Dropping (Deleting) a Trigger
When you no longer need a trigger, you remove it using the DROP
TRIGGER statement.
โโ Safety Check: Use IF EXISTS to prevent errors if the trigger is
already gone.
โโ Identify Clearly: It is recommended to use "dot notation"
(SchemaName.TriggerName) so MySQL knows exactly which one to
delete.
โโ Automatic Deletion: If you delete the whole table (e.g., DROP
TABLE Orders), all triggers attached to that table are automatically
deleted.
๐ถ The "5-Year-Old" Version
Imagine you are playing a game where you put colorful balls into a bucket.
The Trigger is like a Gatekeeper.
โโ You try to throw a Blue Ball (a negative number) into the bucket.
โโ The Gatekeeper stands in front of the bucket (BEFORE INSERT).
โโ He catches the ball in mid-air.
โโ He looks at it and says, "Blue balls are not allowed! I will paint this
ball Red (change it to Zero)."
โโ Then, he drops the Red ball into the bucket.
โโ The bucket never saw the Blue ball; it only received the Red one.
Dropping the Trigger just means telling the Gatekeeper to go home. Now,
whatever ball you throw goes straight into the bucket.
โ๏ธ Practice Exercise
Scenario: You have a table called Staff with a column called
HourlyRate. You want to ensure no one accidentally enters a pay rate
higher than $100. If they do, it should automatically be set to $100.
Task: Fill in the blanks to complete the code based on the notes.
SQL
DELIMITER //
CREATE TRIGGER CapHourlyRate
_______ INSERT -- 1. Should this happen BEFORE or AFTER the data is
saved?
ON Staff
FOR EACH ROW
BEGIN
-- 2. Which modifier do we use to check the incoming value? (NEW or
OLD?)
IF ______.HourlyRate > 100 THEN
SET ______.HourlyRate = 100;
END IF;
END //
DELIMITER ;
โ
Practice Exercise Solution
Here is the completed code for the CapHourlyRate trigger.
โโ Blank 1: BEFORE (We need to catch the high rate before it gets
saved into the database).
โโ Blank 2: NEW (We need to check the new value the user is trying to
type in).
Completed Code:
SQL
DELIMITER //
CREATE TRIGGER CapHourlyRate
BEFORE INSERT
ON Staff
FOR EACH ROW
BEGIN
-- Check the NEW value coming in
IF NEW.HourlyRate > 100 THEN
SET NEW.HourlyRate = 100;
END IF;
END //
DELIMITER ;
๐๏ธ How to Drop This Trigger
If you decided you no longer wanted this rule (for example, if a manager
gets a raise to $150), you would run this command to remove the trigger:
SQL
DROP TRIGGER IF EXISTS Staff.CapHourlyRate;
Breakdown:
โโ IF EXISTS: Prevents an error if you already deleted it.
โโ Staff.CapHourlyRate: Uses the "dot notation"
(SchemaName.TriggerName) to be specific, though just the trigger
name works if you are already inside the correct database.
๐ Comprehensive Notes: MySQL Scheduled Events
1. What is a Scheduled Event?
A scheduled event is a task that runs automatically according to a specific
schedule. Instead of you sitting at the computer to run a command, the
database does it for you at the exact time you set.
โโ They are stored inside the database.
โโ They can run just once or repeat over and over.
2. Two Main Types of Events
1.โ One-Time Events: These happen once and then never again.
โโ Example: "Insert this data exactly one hour from now".
2.โ Recurring Events: These happen repeatedly on a regular basis.
โโ Example: "Generate a report every single week".
3. How to Create an Event
To build an event, you use the CREATE EVENT command.
A. General Syntax Structure
โโ Step 1: Name the event (CREATE EVENT event_name).
โโ Step 2: Set the Schedule (ON SCHEDULE...).
โโ Step 3: Define the Action (DO ...) followed by the SQL logic.
B. Creating a One-Time Event (The "At" Clause) Use the keyword AT
followed by a specific time or timestamp.
โโ Lucky Shrub Example: They need a revenue report generated 12
hours from now.
โโ Code: ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 12
HOUR.
C. Creating a Recurring Event (The "Every" Clause) Use the keyword
EVERY followed by how often it should repeat (e.g., DAY, HOUR, WEEK).
โโ Lucky Shrub Example: A daily check to restock products if inventory
drops below 50.
โโ Code: ON SCHEDULE EVERY 1 DAY.
4. How to Delete (Drop) an Event
If an event is no longer needed, you remove it using DROP EVENT.
โโ Best Practice: Use IF EXISTS to prevent errors if the event is
already gone.
โโ Syntax: DROP EVENT IF EXISTS event_name;.
๐ถ The "5-Year-Old" Version
Imagine you have a Robot Butler.
1. The One-Time Event (The Pizza Timer)
โโ You tell the robot: "In exactly 20 minutes, take the pizza out of the
oven."
โโ The robot waits 20 minutes, takes the pizza out, and then the task is
done. He doesn't do it again tomorrow.
โโ This is ON SCHEDULE AT...
2. The Recurring Event (The Alarm Clock)
โโ You tell the robot: "Every morning at 7:00 AM, wake me up for
school."
โโ The robot does it today, tomorrow, and the next day. He keeps doing
it until you tell him to stop.
โโ This is ON SCHEDULE EVERY...
โ๏ธ Practice Exercise
Scenario: You are managing a "Cleanup" task. You want to delete all old
logs from the SystemLogs table once every week.
Task: Fill in the blanks to complete the code based on the notes.
DELIMITER //
CREATE EVENT ClearOldLogs
ON SCHEDULE ________ 1 WEEK -- (Hint: Is this happening once AT a
time, or EVERY week?)
DO
BEGIN
DELETE FROM SystemLogs WHERE LogDate < NOW() - INTERVAL 1
MONTH;
END //
DELIMITER ;
โ
Practice Exercise Solution
Here is the correct keyword to complete your recurring event:
โโ Blank: EVERY (Because you want this task to repeat automatically on
a schedule, not just happen once).
Completed Code:
SQL
DELIMITER //
CREATE EVENT ClearOldLogs
ON SCHEDULE EVERY 1 WEEK
DO
BEGIN
DELETE FROM SystemLogs WHERE LogDate < NOW() - INTERVAL 1
MONTH;
END //
DELIMITER ;
๐ The "On/Off Switch" (Crucial Step!)
There is one "gotcha" with MySQL Events that trips up almost everyone at
first. Even if you write the perfect code, your event might not run.
Why? because the "Event Scheduler" (the robot butler) might be turned
OFF by default in your database settings.
1. How to check if the robot is awake: Run this command in your SQL
terminal:
SQL
SHOW VARIABLES LIKE 'event_scheduler';
โโ If the value says ON, you are safe.
โโ If the value says OFF or DISABLED, your events will sit there doing
nothing.
2. How to turn the robot ON: If it was off, you can wake it up with this
command:
SQL
SET GLOBAL event_scheduler = ON;
๐ Comprehensive Notes: Overview of
MySQL Triggers
1. What is a Trigger?
A MySQL trigger is a "stored program" attached to a specific table. It works
like an automatic alarm system that activates before or after a specific
event happens to that table.
โโ Supported Events: Triggers can activate on INSERT, UPDATE, or
DELETE.
โโ Row-Level: MySQL triggers happen for each row. If you update 100
rows, the trigger fires 100 times.
2. Why use them? (Key Uses)
Triggers are primarily used to automate tasks that keep data safe and
consistent.
โโ Enforce Rules: Make sure data follows business rules (e.g., "No
negative prices").
โโ Data Integrity: A stronger alternative to simple table constraints.
โโ Audit Trails: Automatically record changes to a separate "Audit"
table (who changed what and when).
โโ Replication: Copy data to other tables to keep everything in sync.
3. Creating a Trigger (The 5 Parts)
To build a trigger, you use the CREATE TRIGGER command. It requires 5
specific pieces of information:
1.โ Name: Must be unique within the database.
2.โ Time: BEFORE or AFTER the action.
3.โ Event: INSERT, UPDATE, or DELETE.
4.โ Table: The specific table to watch (Note: Triggers cannot be used on
temporary tables or views).
5.โ Body: The code to run. (Use BEGIN...END if you have multiple lines
of code).
Syntax Visualized:
SQL
CREATE TRIGGER trigger_name
[BEFORE | AFTER] [INSERT | UPDATE | DELETE]
ON table_name FOR EACH ROW
BEGIN
-- Code goes here
END;
4. The Power of OLD and NEW
Inside the trigger, you need to see the data. MySQL gives you two
keywords (modifiers) to access column values:
โโ OLD: The value before the change (The past).
โโ NEW: The value after the change (The future).
Operati
on
Can use
OLD?
Can use
NEW?
โ No โ
Yes
โ
Yes
UPDAT โ
Yes
E
โ No
DELET โ
Yes
INSER
T
E
Why?
There is no "old" data; it's brand
new.
You can see what it was and what
it will be.
The data is gone; there is no
"new" version.
Export to Sheets
5. Managing Triggers
Listing Triggers: To see what triggers exist in your database, use:โ
SQLโ
SHOW TRIGGERS FROM database_name;
โโ (You can also filter results using LIKE or WHERE).
Removing Triggers: To delete a trigger, use:โ
SQLโ
DROP TRIGGER IF EXISTS trigger_name;
โโ Note: If you delete a table, all triggers attached to it are deleted
automatically.
6. Pros and Cons
Advantages (Pros)
Disadvantages (Cons)
Performance: SQL queries run
faster because the validation
logic is pre-compiled in the
database.
Hidden Errors: Errors can be hard
to find because they happen in the
background (database layer), not the
app layer.
Less Code: You don't have to
write validation code in your app
(Java/Python/JS); the database
handles it.
Overhead: Too many triggers can
slow down the database server.
Consistency: Validation
happens before data is saved,
ensuring bad data never enters.
Limitations: Triggers cannot
perform every type of complex
validation.
Automation: easy to maintain
scheduled tasks or auto-updates.
Export to Sheets
๐ถ The "5-Year-Old" Version
A Trigger is like a Robot Guard Dog.
โโ You give the dog a specific spot to guard (The Table).
โโ You tell the dog when to bark: "Bark Before the mailman comes" or
"Bark After the mailman leaves."
โโ The "OLD" bone: If someone takes a toy away (DELETE), the dog
remembers what the old toy looked like.
โโ The "NEW" bone: If someone brings a new toy (INSERT), the dog
inspects the new toy.
โโ Why is it good? You don't have to watch the door all day. The dog
does it for you automatically!
โโ Why is it bad? If the dog barks too much, it gets noisy and slows
everyone down (Overhead). Also, if the dog bites the mailman, you
might not see it happen immediately (Hidden Errors).
โ๏ธ Practice Exercise
Scenario: You have a Scores table for a game. You want to create a
trigger that prevents a player's score from dropping. If an UPDATE tries to
set a Score lower than it was before, the trigger should force the Score to
remain the OLD value.
Task: Fill in the blanks to complete the code.
SQL
DELIMITER //
CREATE TRIGGER PreventScoreDrop
_______ UPDATE -- 1. Should this be BEFORE or AFTER the change
happens?
ON Scores
FOR EACH ROW
BEGIN
-- 2. Logic: If the NEW score is less than the OLD score...
IF ______.Score < ______.Score THEN
-- 3. Reset the NEW score to match the OLD score
SET ______.Score = ______.Score;
END IF;
END //
DELIMITER ;
โ
Practice Exercise Solution
Here is the completed code to prevent a player's score from dropping.
โโ Blank 1: BEFORE (We must check the score before the change is
saved to stop it).
โโ Blank 2: NEW and OLD (We compare what the user wants to set it to
vs. what it currently is).
โโ Blank 3: NEW and OLD (We overwrite the new bad value with the old
safe value).
Completed Code:
SQL
DELIMITER //
CREATE TRIGGER PreventScoreDrop
BEFORE UPDATE
ON Scores
FOR EACH ROW
BEGIN
-- If the NEW score is less than the OLD score...
IF NEW.Score < OLD.Score THEN
-- Force the NEW score to remain the same as the OLD score
SET NEW.Score = OLD.Score;
END IF;
END //
DELIMITER ;
๐ How to Find Triggers (Listing & Filtering)
Sometimes you might have dozens of triggers in a database and need to
find a specific one. You use the SHOW TRIGGERScommand for this.
1. Listing All Triggers To see everything in your current database:
SQL
SHOW TRIGGERS;
If you want to see triggers from a specific database (like 'LuckyShrub'):
SQL
SHOW TRIGGERS FROM LuckyShrub;
2. Filtering with Patterns (LIKE) If you are looking for triggers related to
"Orders" but don't remember the exact name, you can use the LIKE
keyword with a pattern.
โโ % is a wildcard that matches anything.
โโ Example: Find any trigger that has the word "Order" in its name.
SQL
SHOW TRIGGERS LIKE '%Order%';
3. Filtering with Conditions (WHERE) You can also filter by specific
columns shown in the result list, such as the table the trigger is attached to.
โโ Example: Find all triggers attached specifically to the Employees
table.
SQL
SHOW TRIGGERS WHERE 'Table' = 'Employees';
๐ถ The "5-Year-Old" Version
Searching for Triggers is like using a Flashlight in a Toy Box.
โโ SHOW TRIGGERS: You turn on the light and look at everything in the
box. "Wow, look at all these robots!"
โโ LIKE '%Order%': You tell your friend, "Help me find only the robots
that have a Red Sticker (the word 'Order') on them." You ignore the
blue ones.
โโ WHERE Table = 'Employees': You say, "Only show me the
robots that belong to the Action Figure set."
โ๏ธ Final Practice Question
Scenario: You have a database full of triggers. You suspect there is a
trigger named check_salary_limit, but you aren't sure of the exact
spelling. You want to search for any trigger that starts with the word
"check".
Question: Which command would you use?
A) SHOW TRIGGERS WHERE Name = 'check'; B) SHOW TRIGGERS
LIKE 'check%'; C) SHOW TRIGGERS FROM check;
Answer: B is correct. LIKE 'check%' looks for names starting with
"check" followed by anything else.
Working with triggers
Launch lab
Instructions
Working with triggers
Lucky Shrub need to impose business rules for inserting, updating and deleting product
data in their database. You can help them by implementing triggers on the Products
table.
The Products table contains the following information about each product:
โโ the ProductID,
โโ ProductName,
โโ BuyPrice,
โโ SellPrice ,
โโ and NumberOfItems.
The following screenshot shows the Products table in the Lucky Shrub database:
Note: Before you begin, make sure you know how to access MySQL environment
Prerequisites
To complete this lab, you must have access to the Lucky Shrub database and Products
table in MySQL. The database’s Products table must be populated with the relevant
data. Follow these steps to create and populate the database:
1: Use the following code to create the database:
1
CREATE DATABASE Lucky_Shrub
2: Use the following code to use the database:
1
USE Lucky_Shrub;
3: Use the following code to create the Products table:
1
CREATE TABLE Products (ProductID VARCHAR(10), ProductName VARCHAR(100),BuyPrice
DECIMAL(6,2), SellPrice DECIMAL(6,2), NumberOfItems INT);
4: Use the following code to populate the Products table with data:
INSERT INTO Products (ProductID, ProductName, BuyPrice, SellPrice, NumberOfITems)
VALUES ("P1", "Artificial grass bags ", 40, 50, 100),
("P2", "Wood panels", 15, 20, 250),
("P3", "Patio slates",35, 40, 60),
("P4", "Sycamore trees ", 7, 10, 50),
("P5", "Trees and Shrubs", 35, 50, 75),
("P6", "Water fountain", 65, 80, 15);
5: Create the Notifications table
1
CREATE TABLE Notifications (NotificationID INT AUTO_INCREMENT, Notification
VARCHAR(255), DateTime TIMESTAMP NOT NULL, PRIMARY KEY(NotificationID));
The main objective of this activity:
โโ Develop INSERT, UPDATE and DELETE triggers.
Tasks Instructions
Please attempt the following tasks:
Task 1:
Create an INSERT trigger called ProductSellPriceInsertCheck. This trigger must
check if the SellPrice of the product is less than the BuyPrice after a new product is
inserted in the Products table. If this occurs, then a notification must be added to the
Notifications table to inform the sales department. The sales department can then
ensure that the incorrect values were not inserted by mistake.
The notification message should be in the following format: A SellPrice less than
the BuyPrice was inserted for ProductID + ProductID
The expected output result should be the same as that generated by the values for the
ProductID P7 in the following screenshot.
Task 2:
Create an UPDATE trigger called ProductSellPriceUpdateCheck. This trigger must
check that products are not updated with a SellPrice that is less than or equal to the
BuyPrice. If this occurs, add a notification to the Notifications table for the sales
department so they can ensure that product prices were not updated with the incorrect
values. This trigger sends a notification to the Notifications table that warns the
sales department of the issue.
The notification message should be in the following format: ProductID + was
updated with a SellPrice of + SellPrice + which is the same or
less than the BuyPrice
The expected output result should be the same as that generated by the values for the
ProductID P6 in the following screenshot.
Task 3:
Create a DELETE trigger called NotifyProductDelete. This trigger must insert a
notification in the Notifications table for the sales department after a product has
been deleted from the Products table.
The notification message should be in the following format: The product with a
ProductID + ProductID + was deleted
The expected output result should be the same as that in the following screenshots:
๐งช Lab Overview: Automatic Notifications
The goal of this lab is to help "Lucky Shrub" (a garden supply company)
manage their data automatically. We need to create Triggers that watch
the Products table. If someone enters a price that doesn't make sense
(like selling a product for less than it cost to buy), the system should
automatically write a warning note into a Notifications table.
โ๏ธ Step 1: The Setup (Prerequisites)
Before writing the triggers, you must build the environment. This code
creates the database, the products table, and the empty notifications table
where our triggers will write their messages.
SQL
-- 1. Create and use the database
CREATE DATABASE Lucky_Shrub;
USE Lucky_Shrub;
-- 2. Create the Products table
CREATE TABLE Products (
ProductID VARCHAR(10),
ProductName VARCHAR(100),
BuyPrice DECIMAL(6,2),
SellPrice DECIMAL(6,2),
NumberOfItems INT
);
-- 3. Add some sample data
INSERT INTO Products (ProductID, ProductName, BuyPrice, SellPrice,
NumberOfItems)
VALUES
("P1", "Artificial grass bags ", 40, 50, 100),
("P2", "Wood panels", 15, 20, 250),
("P3", "Patio slates", 35, 40, 60),
("P4", "Sycamore trees ", 7, 10, 50),
("P5", "Trees and Shrubs", 35, 50, 75),
("P6", "Water fountain", 65, 80, 15);
-- 4. Create the Notifications table to store the warnings
CREATE TABLE Notifications (
NotificationID INT AUTO_INCREMENT,
Notification VARCHAR(255),
DateTime TIMESTAMP NOT NULL,
PRIMARY KEY(NotificationID)
);
๐ Task 1: The "New Product" Watchdog
Goal: Create a trigger named ProductSellPriceInsertCheck. The
Rule: When a new product is inserted, check if the SellPrice is lower
than the BuyPrice. If it is, log a notification.
The Solution:
SQL
DELIMITER //
CREATE TRIGGER ProductSellPriceInsertCheck
AFTER INSERT
ON Products FOR EACH ROW
BEGIN
-- Check if the new SellPrice is less than the BuyPrice
IF NEW.SellPrice <= NEW.BuyPrice THEN
INSERT INTO Notifications (Notification, DateTime)
VALUES (
CONCAT('A SellPrice less than the BuyPrice was inserted for
ProductID ', NEW.ProductID),
NOW()
);
END IF;
END //
DELIMITER ;
How to Test It:
SQL
-- Insert a product where SellPrice (40) is less than BuyPrice (50)
INSERT INTO Products (ProductID, ProductName, BuyPrice, SellPrice,
NumberOfItems)
VALUES ("P7", "Bad Product", 50, 40, 100);
-- Check the notification table to see the warning
SELECT * FROM Notifications;
๐ Task 2: The "Price Update" Watchdog
Goal: Create a trigger named ProductSellPriceUpdateCheck. The
Rule: When an existing product is updated, check if the SellPrice is
less than or equal to the BuyPrice. If so, log a notification.
The Solution:
SQL
DELIMITER //
CREATE TRIGGER ProductSellPriceUpdateCheck
AFTER UPDATE
ON Products FOR EACH ROW
BEGIN
-- Check if the updated SellPrice is the same or less than BuyPrice
IF NEW.SellPrice <= NEW.BuyPrice THEN
INSERT INTO Notifications (Notification, DateTime)
VALUES (
CONCAT(NEW.ProductID, ' was updated with a SellPrice of ',
NEW.SellPrice, ' which is the same or less than the BuyPrice'),
NOW()
);
END IF;
END //
DELIMITER ;
How to Test It:
SQL
-- Update Product P6 so its SellPrice (60) is less than its BuyPrice (65)
UPDATE Products SET SellPrice = 60 WHERE ProductID = "P6";
-- Check the notification table
SELECT * FROM Notifications;
๐ Task 3: The "Deletion" Logger
Goal: Create a trigger named NotifyProductDelete. The Rule:
Whenever a product is deleted, simply log a message saying which ID was
removed.
The Solution:
SQL
DELIMITER //
CREATE TRIGGER NotifyProductDelete
AFTER DELETE
ON Products FOR EACH ROW
BEGIN
-- Note: We use 'OLD' here because the row is gone!
INSERT INTO Notifications (Notification, DateTime)
VALUES (
CONCAT('The product with a ProductID ', OLD.ProductID, ' was
deleted'),
NOW()
);
END //
DELIMITER ;
How to Test It:
SQL
-- Delete Product P6
DELETE FROM Products WHERE ProductID = "P6";
-- Check the notification table
SELECT * FROM Notifications;
๐ถ The "5-Year-Old" Version
Imagine you are running a Lemonade Stand.
1.โ The Table (Products): This is your menu board where you write
down "Lemonade: $5".
2.โ The Trigger (The Tattletale): You have a little helper named Timmy.
โโ Task 1: If you write a new item on the board, but you
accidentally make the price too low (so you lose money!),
Timmy sees it and writes a note in his diary: "Boss made a
mistake on the new item!"
โโ Task 2: If you erase an old price and write a new bad price,
Timmy writes another note: "Boss changed the price and now
it's too cheap!"
โโ Task 3: If you completely erase an item from the menu, Timmy
writes: "The lemonade is gone!"
Timmy (the Trigger) does this automatically. You don't have to tell him to
write the note; he just watches the board and does it himself.
โ๏ธ Practice: Your Turn
Scenario: You want to make sure no one accidentally enters a negative
number for NumberOfItems (stock).
Task: Write a BEFORE INSERT trigger. If NEW.NumberOfItems is less
than 0, set it to 0.
Code:
DELIMITER //
CREATE TRIGGER NoNegativeStock
BEFORE INSERT
ON Products FOR EACH ROW
BEGIN
IF NEW.NumberOfItems < 0 THEN
SET NEW.NumberOfItems = 0;
END IF;
END //
DELIMITER ;
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )