Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← MySQL for Data Analysis Expert · Lesson 9 of 15

Module Eight

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
9
Module 8 · MySQL for Data Analysis Expert

⚙️ Module Eight · MySQL for Data Analysis Expert

🤖 Automating with Stored Procedures, Triggers & Events


🌟 Module Introduction

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!


🎯 Learning Objectives

After this module, you will be able to:

  • Create and use stored procedures to save and reuse SQL code.
  • Understand parameters to make procedures flexible.
  • Use triggers to automatically run code when data is added, changed, or deleted.
  • Schedule events to run tasks at specific times.
  • Know when to use each tool.

📖 Warm‑up Story · The School's Automated System

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!


📘 Lesson 1 · What is a Stored Procedure?

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.


📘 Lesson 2 · Creating a Stored Procedure

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.


📘 Lesson 3 · Calling a Stored Procedure

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.


📘 Lesson 4 · Parameters – Making Procedures Flexible

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.


📘 Lesson 5 · Dropping a Stored Procedure

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.


📘 Lesson 6 · What is a Trigger?

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.


📘 Lesson 7 · Creating a Trigger

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.


📘 Lesson 8 · BEFORE vs AFTER Triggers

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.


📘 Lesson 9 · Dropping a Trigger

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.


📘 Lesson 10 · What is an Event?

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.


📘 Lesson 11 · Creating an Event

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.


📘 Lesson 12 · Enabling and Disabling Events

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.


📘 Lesson 13 · Dropping an Event

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.


📘 Lesson 14 · Combining Procedures, Triggers, and Events

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.


📘 Lesson 15 · Best Practices for 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:

  • Keep procedures simple and focused.
  • Test triggers in a development environment first.
  • Schedule events during off-peak hours.
  • Log all automated actions.

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.


📚 Key Vocabulary

Stored Procedure
A saved SQL program that you can run repeatedly.
Parameter
A value you pass to a procedure to make it flexible.
Trigger
SQL that runs automatically when data is added, changed, or deleted.
Event
A scheduled task that runs at a specific time.
BEFORE Trigger
Runs before the event and can modify data.
AFTER Trigger
Runs after the event and cannot modify data.

🧠 Important Concepts

  • Stored procedures save SQL code for reuse.
  • Parameters make procedures flexible.
  • Triggers automatically run on events.
  • Events schedule tasks for automation.
  • Combine all three for powerful automation.

🪜 Step‑by‑Step Explanations

How to create and use a stored procedure:

  1. Write CREATE PROCEDURE name() BEGIN ... END;
  2. Put your SQL inside the BEGIN and END.
  3. Use CALL name(); to run it.

How to create a trigger:

  1. Write CREATE TRIGGER name BEFORE/AFTER INSERT/UPDATE/DELETE ON table FOR EACH ROW BEGIN ... END;
  2. Inside BEGIN/END, write the SQL to execute.
  3. The trigger will run automatically when the event occurs.

How to create an event:

  1. Write CREATE EVENT name ON SCHEDULE EVERY interval DO ...;
  2. Specify the schedule and the SQL task.
  3. Enable the event scheduler if needed.

🌍 Real‑life Examples

  • Amazon uses procedures to process orders, triggers to update inventory, and events to send shipping updates.
  • Banks use procedures for monthly interest calculations.
  • Telecom companies use triggers to manage prepaid balances.

🇳🇬 Nigerian Examples

  • Flutterwave uses procedures to process payments.
  • MTN uses triggers to update data balances.
  • JAMB uses events to generate exam schedules.

🎈 Fun Examples for Children

  • Create a procedure to show your favourite toys.
  • Create a trigger that says "Yay!" when you add a new game.
  • Create an event that reminds you to do homework every day.

🏠 Everyday Examples

  • When you add a new contact, a trigger backs up the old list.
  • Your phone runs an event to clean up old messages every week.
  • Your game uses a procedure to save your progress.

👩‍🏫 Teacher Notes

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.


👨‍👩‍👧‍👦 Parent Tips

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.


💡 Interesting Facts

  • Stored procedures were introduced in SQL in the 1980s.
  • Triggers can be used to enforce complex business rules.
  • Events are also called scheduled jobs.

🧐 Did You Know?

  • Did you know that you can call a stored procedure from within another procedure?
  • Did you know that triggers can be nested?

🔔 Remember This

  • Procedures save SQL code for reuse.
  • Triggers run automatically on data changes.
  • Events schedule tasks at specific times.
  • Use parameters to make procedures flexible.

❌ Common Mistakes

  • Forgetting the DELIMITER: In MySQL, you must change the delimiter when creating procedures or triggers.
  • Using wrong trigger timing: BEFORE vs AFTER – choose the right one.
  • Not checking for existing objects: Use DROP IF EXISTS.
  • Making triggers too complex: Keep them simple to avoid performance issues.

✅ Best Practices

  • Use meaningful names for procedures, triggers, and events.
  • Test in a development environment first.
  • Keep procedures and triggers short.
  • Log actions for debugging.
  • Schedule events during off-peak hours.

📊 ASCII Diagrams & Illustrations

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)           |
+---------------------------+

📋 Comparison Table: Procedures vs Triggers vs Events

FeatureProcedureTriggerEvent
When runsWhen calledOn data changeOn schedule
Can accept parametersYesNoNo
Can be reusedYesNo (automatic)Yes (scheduled)
Used forReusable logicAutomatic actionsScheduled tasks

📝 End‑of‑Module Summary

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!


❓ Frequently Asked Questions

  1. What is a stored procedure? – A saved SQL program.
  2. How do I run a procedure? – Use CALL procedure_name();
  3. What is a parameter? – A value passed to a procedure to make it flexible.
  4. What is a trigger? – SQL that runs automatically on data changes.
  5. What is the difference between BEFORE and AFTER? – BEFORE runs before the event, AFTER runs after.
  6. What is an event? – A scheduled task.
  7. How do I create an event? – Use CREATE EVENT.
  8. Can triggers call procedures? – Yes.
  9. Can events call procedures? – Yes.
  10. Why use automation? – To save time and avoid errors.

📝 Review Questions

  1. What is a stored procedure?
  2. How do you call a stored procedure?
  3. What is a parameter?
  4. What is a trigger?
  5. What are the three events that can fire a trigger?
  6. What is the difference between BEFORE and AFTER?
  7. What is an event?
  8. How do you schedule an event?
  9. How do you drop a procedure?
  10. How do you drop a trigger?
  11. How do you drop an event?
  12. Why would you use a stored procedure?
  13. Give an example of a trigger at school.
  14. Give an example of an event at home.
  15. How do procedures, triggers, and events work together?

✏️ Fill‑in‑the‑Blank

  1. CREATE ________ my_proc() BEGIN SELECT * FROM students; END;
  2. CALL ________(); (to run a procedure)
  3. CREATE TRIGGER reduce_stock ________ INSERT ON sales ...
  4. DROP ________ my_trigger;
  5. CREATE ________ daily_backup ON SCHEDULE EVERY 1 DAY DO ...

✅ True or False

  1. Stored procedures can take parameters. (True)
  2. Triggers can be called manually. (False)
  3. Events run on a schedule. (True)
  4. AFTER triggers can modify the data. (False)
  5. BEFORE triggers run after the event. (False)

🔢 Multiple Choice Questions

  1. Which command creates a stored procedure?
    A) CREATE PROCEDURE B) CREATE TRIGGER C) CREATE EVENT D) CREATE VIEW
  2. Which command runs a stored procedure?
    A) RUN B) EXECUTE C) CALL D) START
  3. Which keyword passes a value to a procedure?
    A) OUT B) IN C) PARAM D) VALUE
  4. Which event can fire a trigger?
    A) SELECT B) INSERT C) JOIN D) VIEW
  5. Which trigger runs before the event?
    A) AFTER B) BEFORE C) INSTEAD OF D) ON
  6. Which statement schedules a task?
    A) CREATE PROCEDURE B) CREATE TRIGGER C) CREATE EVENT D) CREATE INDEX
  7. Which command removes a procedure?
    A) DROP PROCEDURE B) DELETE PROCEDURE C) REMOVE PROCEDURE D) DROP TRIGGER
  8. Which command removes a trigger?
    A) DROP TRIGGER B) DELETE TRIGGER C) REMOVE TRIGGER D) DROP EVENT
  9. Which command removes an event?
    A) DROP EVENT B) DELETE EVENT C) REMOVE EVENT D) DROP PROCEDURE
  10. Which timing allows modification of data?
    A) BEFORE B) AFTER C) Both D) Neither
  11. Which of these can be used with an event?
    A) SELECT B) INSERT C) UPDATE D) All of the above
  12. What does CALL do?
    A) Runs a procedure B) Creates a trigger C) Schedules an event D) Drops a table
  13. Which is NOT a trigger event?
    A) INSERT B) UPDATE C) DELETE D) SELECT
  14. Which is used to enable/disable an event?
    A) ALTER EVENT B) CHANGE EVENT C) MODIFY EVENT D) UPDATE EVENT
  15. Why use automation?
    A) To save time B) To reduce errors C) To improve consistency D) All of the above

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


🔗 Matching Exercises

Match the term to its description:

TermDescription
ProcedureSaved SQL program
TriggerAutomatic on data change
EventScheduled task
ParameterInput to procedure
BEFORERuns before event

📝 Short Answer Questions

  1. Write a stored procedure to get all students from JSS1.
  2. Write a trigger that updates the class average when a new grade is added.
  3. Write an event that runs every day at 10pm to clean up old logs.
  4. Explain the difference between a procedure and a trigger.
  5. Why would you use an event instead of a trigger?

🎭 Scenario‑based Exercises

  1. You have a library database. Create a procedure to count books by category. Create a trigger to log when a book is borrowed. Create an event to send a reminder for overdue books.
  2. You have a school database. Create a procedure to generate a report card. Create a trigger to update the grade average. Create an event to email the principal weekly.
  3. You have a supermarket. Create a procedure to reorder stock. Create a trigger to reduce stock when a sale is made. Create an event to run the reorder procedure every Monday.

👥 Group Activity

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.


🧑 Individual Activity

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.


💬 Classroom Discussion Questions

  • Why is automation important in databases?
  • What could go wrong if a trigger is poorly written?
  • How do events make life easier for a database administrator?

🛠️ Mini Project

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.


💻 Practical Assignment

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.


⚡ Challenge Exercise

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.


📌 Quiz Answers

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.


🔑 Key Takeaways

  • Stored procedures save and reuse SQL code.
  • Triggers automate actions on data changes.
  • Events schedule tasks at specific times.
  • Combine them for full automation.
  • Always test before deploying to production.

🚀 Preparation for the Next Module

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!

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→