Chapter 16: Triggers & Events

Triggers and Events are like hidden robots inside MySQL that watch for certain things to happen and then automatically run code for you.

  • Triggers → React to data changes (INSERT, UPDATE, DELETE)
  • Events → Run scheduled tasks at specific times (like cron jobs in the database)

These two features make your database self-maintaining, audit-proof, and super efficient.

Let’s dive in step-by-step!

1. What is a Trigger? (Real-life analogy)

Imagine your coaching class has a rule: “Every time a new student enrolls (INSERT into enrollments), automatically update the student’s last_enrollment_date in the students table.”

Instead of remembering to do this manually every time, you create a trigger that automatically runs whenever someone inserts into enrollments.

Triggers fire automatically when:

  • INSERT → new row added
  • UPDATE → row changed
  • DELETE → row removed

And they can run BEFORE the action (to modify data) or AFTER (to log or react).

2. CREATE TRIGGER – Basic Syntax

Syntax:

SQL

Important terms:

  • NEW → refers to the new row being inserted/updated
  • OLD → refers to the old row being updated/deleted

Example 1 – BEFORE INSERT trigger: Automatically set enrollment_date to today

SQL

Now whenever you do:

SQL

The enrollment_date will automatically be set to today — even if you forget to mention it!

Example 2 – AFTER INSERT trigger: Update student’s last_enrollment_date First, add a column to students:

SQL

Now create the trigger:

SQL

Now every enrollment automatically updates the student’s last enrollment date!

Example 3 – BEFORE UPDATE trigger: Prevent fees_paid from being negative

SQL

Try:

SQL

→ You’ll get an error! (Great for data validation)

Example 4 – AFTER DELETE trigger: Log deleted enrollments First, create a log table:

SQL

Now the trigger:

SQL

Delete a row:

SQL

Check log:

SQL

3. CREATE EVENT – Scheduled Tasks (Like Cron Jobs)

Events are scheduled SQL tasks that run at specific times or intervals.

Syntax:

SQL

Example 1 – Daily event: Mark inactive students who haven’t enrolled in 365 days

SQL

This runs every day and automatically deactivates students who haven’t enrolled in over a year.

Example 2 – Monthly event: Reset fees_paid to 0 on the 1st of every month (for demo)

SQL

4. Scheduling & Monitoring Events

Enable event scheduler (very important – off by default!):

SQL

Check if it’s running:

SQL

See all events:

SQL

Drop an event:

SQL

Disable an event temporarily:

SQL

That’s it for Chapter 16! 🎉 You now know how to make your database automatically enforce rules, log changes, clean up old data, and run scheduled jobs — like a true professional DBA!

Homework for today (do it right now – very important!) Run these and paste the output of the final SELECTs:

SQL

Paste the results of the two SELECTs — I’ll check if the triggers worked!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *