Hello, data engineer! In the past modules, we learned to ask questions, speed up searches, and keep data safe. Now we are going to make the database do things automatically!
We will learn about stored procedures (saved programs that run on the database), triggers (actions that happen automatically when data changes), and events (scheduled tasks that run at specific times).
These tools will make your database smarter and reduce the work you have to do. Let's get started!
After this module, you will be able to:
In a big school in Ibadan, the principal is tired of manually updating grades and sending reports. Every day, she spends hours copying data.
One day, the IT teacher says, "Let's use stored procedures to save the report query. Then we can run it with one click! And we can use triggers to automatically update the class average when a new grade is entered. Finally, we can set up an event to send a report every Friday at 4pm."
Now the principal is happy because the database does all the work automatically!
Definition: A stored procedure is a saved set of SQL statements that you can run like a program. It is stored in the database.
Why important: It saves time – you write the code once and run it many times.
Simple explanation: Imagine you have a recipe for your favourite meal. You write it down once, and then you can follow it anytime. A stored procedure is like a recipe for SQL.
Real‑life example: A bank has a stored procedure to calculate interest on all accounts every month.
School example: A stored procedure to generate report cards for all students.
Home example: A stored procedure to update your chore list every week.
Nigerian example: A Nigerian fintech uses a stored procedure to process daily transactions.
+---------------------------+
| Stored Procedure |
| "get_student_report" |
| SELECT name, score |
| FROM students |
| WHERE class = 'JSS1'; |
+---------------------------+
|
V
+---------------------------+
| Run it anytime: |
| CALL get_student_report();|
+---------------------------+
✅ Mini summary: A stored procedure is a saved SQL program that you can run repeatedly.
Definition: Use CREATE PROCEDURE to define a new procedure.
Why important: This is how we save our SQL code for reuse.
Simple explanation: You write CREATE PROCEDURE name() BEGIN ... END; and put your SQL inside.
Real‑life example: CREATE PROCEDURE get_all_customers() BEGIN SELECT * FROM customers; END;
School example: CREATE PROCEDURE get_students() BEGIN SELECT * FROM students; END;
Home example: CREATE PROCEDURE get_snacks() BEGIN SELECT * FROM fridge WHERE type='snack'; END;
Nigerian example: CREATE PROCEDURE get_lagos_voters() BEGIN SELECT * FROM voters WHERE state='Lagos'; END;
DELIMITER //
CREATE PROCEDURE get_students()
BEGIN
SELECT * FROM students;
END //
DELIMITER ;
✅ Mini summary: CREATE PROCEDURE saves a SQL query for later use.
Definition: Use CALL to run a stored procedure.
Why important: This is how we execute the saved code.
Simple explanation: You just say CALL procedure_name(); and it runs.
Real‑life example: CALL get_all_customers(); shows all customers.
School example: CALL get_students(); shows all students.
Home example: CALL get_snacks(); shows all snacks.
Nigerian example: CALL get_lagos_voters(); shows Lagos voters.
CALL get_students();
✅ Mini summary: CALL runs a stored procedure.
Definition: Parameters are like inputs you give to a procedure to change its behavior.
Why important: They make procedures reusable for different cases.
Simple explanation: Like a recipe where you can change the ingredients. You say "show me students in class X" where X is a parameter.
Real‑life example: CREATE PROCEDURE get_customers_by_city(IN city_name VARCHAR(50)) BEGIN SELECT * FROM customers WHERE city = city_name; END;
School example: CREATE PROCEDURE get_students_by_class(IN class_name VARCHAR(10)) BEGIN SELECT * FROM students WHERE class = class_name; END;
Home example: CREATE PROCEDURE get_items_by_type(IN type_name VARCHAR(20)) BEGIN SELECT * FROM fridge WHERE type = type_name; END;
Nigerian example: CREATE PROCEDURE get_voters_by_state(IN state_name VARCHAR(50)) BEGIN SELECT * FROM voters WHERE state = state_name; END;
CREATE PROCEDURE get_students_by_class(IN class_name VARCHAR(10))
BEGIN
SELECT * FROM students WHERE class = class_name;
END;
CALL get_students_by_class('JSS1');
✅ Mini summary: Parameters let you pass values to a procedure for flexible queries.
Definition: Use DROP PROCEDURE to delete a procedure.
Why important: If you no longer need a procedure, you can remove it.
Simple explanation: Like throwing away a recipe you don't use anymore.
Real‑life example: DROP PROCEDURE get_all_customers;
School example: DROP PROCEDURE get_students;
Home example: DROP PROCEDURE get_snacks;
Nigerian example: DROP PROCEDURE get_lagos_voters;
DROP PROCEDURE get_students_by_class;
✅ Mini summary: DROP PROCEDURE removes a stored procedure.
Definition: A trigger is a set of SQL statements that automatically run when a certain event happens on a table (INSERT, UPDATE, or DELETE).
Why important: Triggers let you enforce rules and automate actions without writing extra code.
Simple explanation: Imagine a spring-loaded trap – when someone opens a door (event), the trap triggers (action).
Real‑life example: When a product is sold (INSERT into sales), a trigger reduces the stock in the products table.
School example: When a new student is added, a trigger creates a record in the attendance table.
Home example: When you eat a snack (UPDATE quantity), a trigger alerts you to buy more.
Nigerian example: When a voter registers, a trigger sends a confirmation SMS.
+---------------------------+ +---------------------------+ | Event: INSERT on sales | ---> | Trigger: UPDATE stock | | (a sale happens) | | (reduce product quantity) | +---------------------------+ +---------------------------+
✅ Mini summary: A trigger runs automatically when data is added, changed, or deleted.
Definition: Use CREATE TRIGGER to define a trigger. You specify the event (INSERT, UPDATE, DELETE), the timing (BEFORE or AFTER), and the table.
Why important: It's how we set up automatic actions.
Simple explanation: You say "Before inserting a sale, check if stock is available."
Real‑life example: CREATE TRIGGER reduce_stock AFTER INSERT ON sales FOR EACH ROW UPDATE products SET stock = stock - NEW.quantity WHERE id = NEW.product_id;
School example: CREATE TRIGGER update_attendance AFTER INSERT ON students FOR EACH ROW INSERT INTO attendance (student_id) VALUES (NEW.id);
Home example: CREATE TRIGGER alert_low_stock AFTER UPDATE ON fridge FOR EACH ROW IF NEW.quantity < 5 THEN INSERT INTO alerts (message) VALUES ('Low stock!'); END IF;
Nigerian example: CREATE TRIGGER log_voter_registration AFTER INSERT ON voters FOR EACH ROW INSERT INTO logs (action) VALUES ('Voter registered');
DELIMITER //
CREATE TRIGGER reduce_stock
AFTER INSERT ON sales
FOR EACH ROW
BEGIN
UPDATE products SET stock = stock - NEW.quantity
WHERE id = NEW.product_id;
END //
DELIMITER ;
✅ Mini summary: CREATE TRIGGER sets up automatic actions on tables.
Definition: BEFORE triggers run before the event, AFTER triggers run after.
Why important: The timing determines what you can do – BEFORE can change the data, AFTER cannot.
Simple explanation: BEFORE is like checking if you have money before buying; AFTER is like updating your balance after buying.
Real‑life example: BEFORE INSERT – check if a customer exists. AFTER INSERT – send a welcome email.
School example: BEFORE UPDATE – check if grade is valid. AFTER UPDATE – update the class average.
Home example: BEFORE DELETE – backup the row. AFTER DELETE – log the action.
Nigerian example: BEFORE INSERT – validate BVN. AFTER INSERT – send SMS.
+---------------------------+ +---------------------------+ | BEFORE Trigger | | AFTER Trigger | | (runs before event) | | (runs after event) | | Can modify data | | Cannot modify data | +---------------------------+ +---------------------------+
✅ Mini summary: BEFORE triggers run before the change, AFTER triggers run after.
Definition: Use DROP TRIGGER to remove a trigger.
Why important: If you no longer need a trigger, you can drop it.
Simple explanation: Like removing a sensor that no longer needs to trigger.
Real‑life example: DROP TRIGGER reduce_stock;
School example: DROP TRIGGER update_attendance;
Home example: DROP TRIGGER alert_low_stock;
Nigerian example: DROP TRIGGER log_voter_registration;
DROP TRIGGER reduce_stock;
✅ Mini summary: DROP TRIGGER removes a trigger.
Definition: An event is a task that runs at a scheduled time, like a cron job in MySQL.
Why important: It automates regular maintenance and reporting.
Simple explanation: Like setting an alarm to wake you up every morning – the database runs a task at a specific time.
Real‑life example: A daily event to back up the database at 2am.
School example: An event every Friday to generate report cards.
Home example: An event every Sunday to clean up old files.
Nigerian example: An event to send daily transaction summaries to the bank manager.
+---------------------------+
| Event Scheduler |
| Runs at scheduled times |
| e.g., every day at 2am |
+---------------------------+
|
V
+---------------------------+
| Task: Backup database |
| Generate report |
| Send email |
+---------------------------+
✅ Mini summary: An event schedules a task to run at a specific time.
Definition: Use CREATE EVENT to define a scheduled task.
Why important: It allows automation of repetitive tasks.
Simple explanation: You say "Run this SQL every day at 2am".
Real‑life example: CREATE EVENT daily_backup ON SCHEDULE EVERY 1 DAY STARTS '2025-01-01 02:00:00' DO ...
School example: CREATE EVENT weekly_report ON SCHEDULE EVERY 1 WEEK STARTS '2025-01-06 16:00:00' DO CALL generate_report();
Home example: CREATE EVENT cleanup ON SCHEDULE EVERY 1 WEEK DO DELETE FROM logs WHERE date < NOW() - INTERVAL 7 DAY;
Nigerian example: CREATE EVENT daily_transaction_summary ON SCHEDULE EVERY 1 DAY STARTS '2025-01-01 23:59:00' DO INSERT INTO summaries SELECT ...;
CREATE EVENT daily_cleanup ON SCHEDULE EVERY 1 DAY STARTS '2025-01-01 00:00:00' DO DELETE FROM temp_table WHERE created_at < NOW() - INTERVAL 1 DAY;
✅ Mini summary: CREATE EVENT schedules a task to run at a set time.
Definition: You can enable or disable events with ALTER EVENT.
Why important: It gives you control over when events run.
Simple explanation: You can pause an event without deleting it.
Real‑life example: ALTER EVENT daily_backup DISABLE; to stop backups temporarily.
School example: ALTER EVENT weekly_report ENABLE; to start it again.
Home example: ALTER EVENT cleanup DISABLE; to stop cleanup.
Nigerian example: ALTER EVENT daily_summary ENABLE; to enable it.
ALTER EVENT daily_cleanup DISABLE; ALTER EVENT daily_cleanup ENABLE;
✅ Mini summary: ALTER EVENT enables or disables scheduled events.
Definition: Use DROP EVENT to remove an event.
Why important: If you no longer need a scheduled task, you can delete it.
Simple explanation: Like deleting an alarm on your phone.
Real‑life example: DROP EVENT daily_backup;
School example: DROP EVENT weekly_report;
Home example: DROP EVENT cleanup;
Nigerian example: DROP EVENT daily_summary;
DROP EVENT daily_cleanup;
✅ Mini summary: DROP EVENT removes a scheduled event.
Definition: We can use all three together to build a fully automated system.
Why important: Real-world applications use them in combination.
Simple explanation: Use procedures for reusable logic, triggers for instant reactions, and events for scheduled tasks.
Real‑life example: An e‑commerce system: trigger updates stock when an order is placed, procedure generates monthly sales report, event sends the report every month.
School example: Trigger logs grade changes, procedure calculates class average, event emails the principal weekly.
Home example: Trigger updates chore status, procedure generates weekly summary, event sends reminder.
Nigerian example: Trigger logs transactions, procedure computes daily balance, event sends report to the bank manager.
+---------------------------+ +---------------------------+
| Trigger: log changes | | Procedure: generate report|
| (on INSERT/UPDATE/DELETE) | | (reusable SQL logic) |
+---------------------------+ +---------------------------+
| |
V V
+---------------------------+ +---------------------------+
| Event: runs at scheduled |----->| Calls procedure, sends |
| time (e.g., daily) | | report via email |
+---------------------------+ +---------------------------+
✅ Mini summary: Triggers, procedures, and events work together for full automation.
Definition: Best practices help you use these tools effectively and safely.
Why important: They prevent errors and keep the system running smoothly.
Simple explanation: Like following safety rules when using tools.
Best practices:
Real‑life example: A bank tests new triggers on a test server before production.
School example: The IT teacher tests procedures on sample data.
Home example: You test a new event on a small dataset.
Nigerian example: A fintech company runs events at midnight to avoid affecting users.
+---------------------------+ +---------------------------+ | Development | | Production | | (test first) | ---> | (deploy after testing) | +---------------------------+ +---------------------------+
✅ Mini summary: Best practices ensure safe and effective automation.
How to create and use a stored procedure:
CREATE PROCEDURE name() BEGIN ... END;CALL name(); to run it.How to create a trigger:
CREATE TRIGGER name BEFORE/AFTER INSERT/UPDATE/DELETE ON table FOR EACH ROW BEGIN ... END;How to create an event:
CREATE EVENT name ON SCHEDULE EVERY interval DO ...;Use the recipe analogy for procedures. Demonstrate triggers with real-time examples (like a doorbell). Use a countdown timer to explain events. Encourage students to think of automation in their daily lives. Use group activities to design a small automated system.
Relate procedures to daily routines (like making breakfast). Explain triggers as "if this, then that" rules. Discuss events as reminders or alarms. Help your child think of ways to automate tasks at home.
DROP IF EXISTS.Procedure flow:
+---------------------------+
| CREATE PROCEDURE |
| get_students() |
| BEGIN |
| SELECT * FROM students; |
| END |
+---------------------------+
|
V
+---------------------------+
| CALL get_students(); |
| (runs the SQL) |
+---------------------------+
Trigger flow:
+---------------------------+ +---------------------------+
| Event: INSERT on sales | ---> | Trigger: reduce_stock |
| (a sale happens) | | (runs automatically) |
+---------------------------+ +---------------------------+
|
V
+---------------------------+
| Update products table |
| (stock is reduced) |
+---------------------------+
Event flow:
+---------------------------+
| Event Scheduler |
| Runs every day at 2am |
+---------------------------+
|
V
+---------------------------+
| Task: Backup database |
| (automatically) |
+---------------------------+
| Feature | Procedure | Trigger | Event |
|---|---|---|---|
| When runs | When called | On data change | On schedule |
| Can accept parameters | Yes | No | No |
| Can be reused | Yes | No (automatic) | Yes (scheduled) |
| Used for | Reusable logic | Automatic actions | Scheduled tasks |
In this module, we explored the powerful world of automation in MySQL. Stored procedures let us save and reuse SQL code, making our work faster and more consistent. Triggers automatically run when data changes, allowing us to enforce rules and perform actions without manual intervention. Events schedule tasks to run at specific times, perfect for regular maintenance and reporting.
We learned how to create, call, and drop procedures, how to set up triggers with BEFORE and AFTER timing, and how to schedule events. We also saw how these tools can work together to build a fully automated system.
With these skills, you are now able to make your database work smart, not hard!
CALL procedure_name();CREATE EVENT.Answers: 1-A, 2-C, 3-B, 4-B, 5-B, 6-C, 7-A, 8-A, 9-A, 10-A, 11-D, 12-A, 13-D, 14-A, 15-D
Match the term to its description:
| Term | Description |
|---|---|
| Procedure | Saved SQL program |
| Trigger | Automatic on data change |
| Event | Scheduled task |
| Parameter | Input to procedure |
| BEFORE | Runs before event |
In groups, design a small automated system for a school. Divide roles: one group writes procedures, one writes triggers, one writes events. Combine them to show a complete automated system. Present to the class.
Create a stored procedure to add a new student. Create a trigger that logs the addition. Create an event that runs every night to backup the student table.
Build a small e‑commerce system. Tables: products, orders, order_items. Create procedures: place_order, get_total_sales. Create triggers: update_stock_after_order, log_order. Create event: generate_daily_sales_report.
Using MySQL, create a "library" database. Create a procedure to add a book. Create a trigger to log when a book is borrowed. Create an event to run a report every week. Test all components.
Write a stored procedure that transfers money between two accounts. Include validation (sufficient balance, accounts exist). Create a trigger that logs all transfers. Create an event that runs daily to compute interest and add it to accounts.
Multiple choice answers are given above. Fill-in-the-blank: 1. PROCEDURE, 2. my_proc, 3. AFTER, 4. TRIGGER, 5. EVENT. True/False: 1T, 2F, 3T, 4F, 5F.
In Module 9, we will dive into performance tuning and query optimization. We will learn how to make queries even faster using EXPLAIN, query caching, and optimization techniques. Get ready to become a performance expert!
🎉 Congratulations! You have finished Module 8. You are now a master of automation – making your database work for you. Keep learning and automating!