Introduction to MySQL Event Scheduler
Course: MySQL Training
Topic: Introduction to MySQL Event Scheduler
Course Link: MySQL Training Course
Demo Link: Register for a Course Demo
Official Reference: MySQL Event Scheduler Documentation
1. Introduction to MySQL Event Scheduler
The MySQL Event Scheduler is a database feature that automatically executes SQL statements according to a predefined schedule. It allows developers and database administrators to automate repetitive database tasks without manually running SQL queries each time.
For example, an online shopping application may need to remove expired temporary records every day, generate daily sales summaries, update reporting tables, or archive old information. The MySQL Event Scheduler can perform these operations at scheduled intervals.
A scheduled task in MySQL is called an event. An event contains an SQL statement or a group of statements and specifies when and how often those statements should execute.
The Event Scheduler is conceptually similar to a cron job in Linux or a scheduled task in Windows. However, MySQL events are managed directly by the MySQL database server.
1.1 Simple Example
CREATE EVENT daily_cleanup
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM temporary_data
WHERE created_at < NOW() - INTERVAL 7 DAY;
This example creates an event that runs daily and attempts to delete temporary records older than seven days. The event runs only when the Event Scheduler is enabled and the event is enabled.
2. Learning Objectives
After completing this topic, you will be able to:
- Understand the meaning and purpose of the MySQL Event Scheduler.
- Differentiate scheduled events from triggers and stored procedures.
- Understand one-time and recurring events.
- Check whether the Event Scheduler is enabled.
- Create scheduled tasks using CREATE EVENT.
- Use AT, EVERY, STARTS, and ENDS to define event schedules.
- Enable, disable, modify, inspect, and drop events.
- Automate routine database maintenance tasks.
- Understand permissions, time zones, and execution behavior.
- Apply the Event Scheduler in practical database projects.
3. What Is a MySQL Event?
A MySQL event is a named database object containing one or more SQL statements that execute automatically at a specified time or at recurring intervals.
Events are associated with a database schema. Each event has a name, schedule, SQL action, and status. Depending on its schedule, an event may execute once or repeat regularly.
3.1 Key Characteristics of MySQL Events
- Events are stored and managed by the MySQL server.
- They execute according to a time-based schedule.
- They can execute once or repeatedly.
- They can perform supported SQL operations such as INSERT, UPDATE, and DELETE.
- They can contain multiple statements using BEGIN and END.
- They can be enabled, disabled, altered, or dropped.
- They require the Event Scheduler to be enabled before they can execute.
- They execute using the security context of their defined definer.
3.2 Examples of Scheduled Database Tasks
| Task |
Schedule |
Purpose |
| Temporary data cleanup |
Daily |
Remove expired temporary records. |
| Sales summary generation |
Every hour |
Update summary information for reporting. |
| Inactive session cleanup |
Every 15 minutes |
Remove expired application sessions. |
| Monthly archiving |
Monthly |
Move eligible historical records into an archive. |
| Scheduled status update |
Every day |
Update records based on a date condition. |
| Database reporting |
Daily or weekly |
Generate records used by reporting applications. |
4. Understanding the Event Scheduler
The Event Scheduler is the MySQL server component responsible for checking scheduled events and executing their SQL actions when they become due.
Creating an event does not guarantee that it will run. The Event Scheduler must be enabled, the event must be enabled, and the event's SQL action must have the required permissions and valid dependencies.
4.1 How the Event Scheduler Works
- A database administrator or developer creates an event.
- The event definition is stored in the database.
- The event specifies its execution time or repeating interval.
- The MySQL Event Scheduler monitors enabled events.
- When an event becomes due, MySQL executes its defined SQL action.
- The event completes its action and, if recurring, waits for its next scheduled execution.
- Event metadata can be inspected to review its schedule, status, and definition.
4.2 Event Scheduler vs Scheduled Event
| Term |
Meaning |
| Event Scheduler |
The MySQL server component that manages scheduled execution. |
| Event |
A named database object containing a scheduled SQL action. |
| Event schedule |
Defines when and how frequently the event should execute. |
| Event body |
The SQL statement or compound statement executed by the event. |
5. Checking Whether the Event Scheduler Is Enabled
Before creating scheduled database tasks, check the current Event Scheduler status.
5.1 Check the Event Scheduler Setting
SHOW VARIABLES LIKE 'event_scheduler';
The result displays the current value of the event_scheduler system variable.
| Value |
Meaning |
| ON |
The Event Scheduler is enabled. |
| OFF |
The Event Scheduler is disabled. |
| DISABLED |
The Event Scheduler is disabled at server startup and cannot be enabled through the ordinary runtime setting. |
5.2 Enable the Event Scheduler
SET GLOBAL event_scheduler = ON;
This command enables the Event Scheduler at runtime when the server configuration and privileges permit it. It generally requires an account with the appropriate system-variable privilege.
Important: A runtime setting may not persist after a server restart. To configure the Event Scheduler to start automatically, set event_scheduler=ON in the MySQL server configuration file when appropriate, and restart or reconfigure the server according to your environment.
5.3 Verify the Setting Again
SHOW VARIABLES LIKE 'event_scheduler';
Confirm that the returned value is ON before testing a scheduled event.
6. Creating Your First MySQL Event
The CREATE EVENT statement creates a new scheduled event. A basic event requires a name, an ON SCHEDULE clause, and a DO clause.
6.1 Basic Syntax
CREATE EVENT event_name
ON SCHEDULE schedule
DO
sql_statement;
6.2 Explanation of the Syntax
| Component |
Description |
| CREATE EVENT |
Creates a scheduled event. |
| event_name |
The unique event name within its database schema. |
| ON SCHEDULE |
Specifies when and how frequently the event executes. |
| schedule |
Contains the one-time or recurring schedule definition. |
| DO |
Introduces the SQL action to execute. |
| sql_statement |
The database operation performed by the event. |
6.3 Example: One-Time Event
CREATE EVENT one_time_update
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
UPDATE system_settings
SET setting_value = 'Updated'
WHERE setting_name = 'status';
This event is scheduled to run once, approximately one hour after its schedule is established. The example assumes that the system_settings table and the specified columns already exist.
7. Understanding One-Time Events
A one-time event executes once at a specified date and time. Use the AT clause to define when the event should run.
7.1 Syntax
CREATE EVENT event_name
ON SCHEDULE AT timestamp
DO
sql_statement;
7.2 Example: Run an Event After 10 Minutes
CREATE EVENT update_status_once
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 10 MINUTE
DO
UPDATE system_settings
SET setting_value = 'Scheduled Update'
WHERE setting_name = 'status';
The event is scheduled for a time ten minutes after its schedule is created. The table and row referenced in the example must exist, and the event's definer must have the necessary privileges.
7.3 Example: Run at a Specific Date and Time
CREATE EVENT scheduled_status_update
ON SCHEDULE AT '2027-01-15 09:00:00'
DO
UPDATE system_settings
SET setting_value = 'January Update'
WHERE setting_name = 'status';
The event is scheduled for the specified date and time, interpreted according to the applicable session time zone when the event is created. Choose a future date appropriate to your environment when testing this example.
8. Understanding Recurring Events
A recurring event executes repeatedly at a defined interval. Use the EVERY clause to specify how frequently it should run.
8.1 Syntax
CREATE EVENT event_name
ON SCHEDULE EVERY interval
DO
sql_statement;
8.2 Common Scheduling Intervals
| Schedule |
Meaning |
| EVERY 10 SECOND |
Runs every ten seconds. |
| EVERY 5 MINUTE |
Runs every five minutes. |
| EVERY 1 HOUR |
Runs every hour. |
| EVERY 1 DAY |
Runs every day. |
| EVERY 1 WEEK |
Runs every week. |
| EVERY 1 MONTH |
Runs every month. |
| EVERY 1 YEAR |
Runs every year. |
8.3 Example: Create a Recurring Event
CREATE EVENT hourly_status_update
ON SCHEDULE EVERY 1 HOUR
DO
UPDATE system_settings
SET setting_value = 'Hourly Check'
WHERE setting_name = 'status';
This event repeats every hour. Unless a STARTS clause specifies a future time, the repeating schedule begins from the current time according to the event's schedule.
9. Using STARTS and ENDS
The STARTS and ENDS clauses help define the active time range of a recurring event.
- STARTS: Specifies when the recurring schedule begins.
- ENDS: Specifies when the recurring schedule stops.
9.1 Example: Start Tomorrow
CREATE EVENT daily_report_event
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
INSERT INTO daily_report_log (report_message, created_at)
VALUES ('Daily report task executed', CURRENT_TIMESTAMP);
This event begins its recurring schedule one day after creation. It assumes the daily_report_log table contains the report_message and created_at columns.
9.2 Example: Schedule an Event for a Limited Period
CREATE EVENT temporary_hourly_task
ON SCHEDULE EVERY 1 HOUR
STARTS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
ENDS CURRENT_TIMESTAMP + INTERVAL 7 DAY
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('temporary_hourly_task', CURRENT_TIMESTAMP);
This event is scheduled to begin one hour after creation and stop at the specified end time, approximately seven days after the schedule is established. The task_log table must exist.
9.3 Using STARTS and ENDS Together
CREATE EVENT weekly_summary_event
ON SCHEDULE EVERY 1 WEEK
STARTS '2027-01-01 08:00:00'
ENDS '2027-06-30 23:59:59'
DO
INSERT INTO summary_log (summary_name, created_at)
VALUES ('Weekly Summary', CURRENT_TIMESTAMP);
This example schedules weekly executions between the defined start and end times. Make sure the chosen dates are suitable for your intended test.
10. Understanding the DO Clause
The DO clause specifies the SQL action executed by an event. It can contain a supported SQL statement or a compound statement with multiple operations.
10.1 Simple UPDATE Statement
CREATE EVENT update_product_status
ON SCHEDULE EVERY 1 DAY
DO
UPDATE products
SET status = 'Review'
WHERE expiry_date < CURRENT_DATE;
This example updates products whose expiry_date is earlier than the current date. It assumes the products table contains status and expiry_date columns.
10.2 Simple INSERT Statement
CREATE EVENT daily_log_event
ON SCHEDULE EVERY 1 DAY
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('Daily Task', CURRENT_TIMESTAMP);
This event inserts a log record each day when the event runs successfully.
10.3 Simple DELETE Statement
CREATE EVENT expired_session_cleanup
ON SCHEDULE EVERY 1 HOUR
DO
DELETE FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
This event removes expired sessions every hour. Review the deletion criteria carefully and test the DELETE condition with a SELECT statement before using cleanup logic in production.
11. Using BEGIN and END for Multiple Statements
An event can execute multiple SQL statements by using a compound statement with BEGIN and END. This is useful when a scheduled task needs to insert a summary record and then clean up temporary data.
11.1 Example
DELIMITER //
CREATE EVENT daily_activity_summary
ON SCHEDULE EVERY 1 DAY
DO
BEGIN
INSERT INTO activity_summary (summary_date, total_sessions)
SELECT CURRENT_DATE, COUNT(*)
FROM user_sessions;
DELETE FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
END//
DELIMITER ;
This event records the number of rows in user_sessions and then deletes expired sessions. The example is illustrative: a production summary should count the intended session subset, and the summary table should have suitable constraints to prevent accidental duplicate daily summaries.
11.2 Why DELIMITER Is Used
In the MySQL command-line client, DELIMITER temporarily changes the statement terminator. It allows semicolons inside the BEGIN...END block without ending the CREATE EVENT statement prematurely.
The delimiter command is a client instruction, not part of the event's stored SQL logic. Some database tools handle statement delimiters differently, so follow the tool's instructions if necessary.
12. Creating a Database for Event Scheduler Practice
In this practical example, an event will periodically write a message to a log table. This provides an easy way to observe whether a scheduled task is executing.
12.1 Create a Database
CREATE DATABASE mysql_event_demo;
USE mysql_event_demo;
12.2 Create a Task Log Table
CREATE TABLE task_log (
log_id INT AUTO_INCREMENT PRIMARY KEY,
task_name VARCHAR(100) NOT NULL,
executed_at DATETIME NOT NULL
) ENGINE = InnoDB;
12.3 Create a Recurring Event
CREATE EVENT log_event_every_minute
ON SCHEDULE EVERY 1 MINUTE
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('Event Scheduler Test', CURRENT_TIMESTAMP);
12.4 Verify the Results
Wait for the scheduled event to run, then execute:
SELECT *
FROM task_log
ORDER BY log_id DESC;
If the Event Scheduler is enabled and the event is enabled with valid permissions, a new log entry should appear each time the event successfully executes.
13. Enabling, Disabling, and Modifying Events
MySQL provides ALTER EVENT for modifying an existing event's properties, including its schedule, action, and enabled status.
13.1 Disable an Event
ALTER EVENT log_event_every_minute DISABLE;
The event definition remains in the database, but it will not execute while disabled.
13.2 Enable an Event
ALTER EVENT log_event_every_minute ENABLE;
This enables the event so that it can execute according to its schedule, provided the Event Scheduler itself is enabled.
13.3 Change the Schedule
ALTER EVENT log_event_every_minute
ON SCHEDULE EVERY 5 MINUTE;
This changes the event to a five-minute recurring schedule.
13.4 Change the Event Action
ALTER EVENT log_event_every_minute
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('Updated Event Task', CURRENT_TIMESTAMP);
This changes the SQL action performed by the event while retaining its existing schedule unless another schedule change is specified.
14. Viewing and Managing Events
14.1 Display Events
SHOW EVENTS;
This command displays scheduled events associated with the current database schema.
14.2 Display Events from a Specific Database
SHOW EVENTS FROM mysql_event_demo;
14.3 Inspect Event Definitions
SHOW CREATE EVENT log_event_every_minute;
This statement displays the SQL definition of the specified event.
14.4 Inspect Event Metadata
SELECT
EVENT_NAME,
EVENT_TYPE,
STATUS,
EXECUTE_AT,
INTERVAL_VALUE,
INTERVAL_FIELD,
STARTS,
ENDS
FROM INFORMATION_SCHEMA.EVENTS
WHERE EVENT_SCHEMA = 'mysql_event_demo';
The metadata fields provide information about the event's type, status, and scheduling details. Values that do not apply to a particular event type may be NULL.
14.5 Drop an Event
DROP EVENT IF EXISTS log_event_every_minute;
This permanently removes the event definition. It does not automatically remove rows that the event previously inserted into task_log.
15. Understanding ON COMPLETION PRESERVE
A one-time event normally disappears after its schedule expires. The ON COMPLETION PRESERVE clause can be used to retain the event definition after completion.
15.1 Example
CREATE EVENT one_time_report
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('One-Time Report', CURRENT_TIMESTAMP);
This event is scheduled to execute once, one day after its schedule is established. ON COMPLETION PRESERVE retains the event definition after completion rather than automatically dropping it.
15.2 Difference Between PRESERVE and NOT PRESERVE
| Option |
Behavior |
| ON COMPLETION PRESERVE |
Retains the event definition after its schedule expires. |
| ON COMPLETION NOT PRESERVE |
Allows the completed event to be dropped; this is the default behavior. |
16. Practical Use Cases of MySQL Event Scheduler
16.1 Automatic Cleanup of Expired Sessions
Web applications often store session information in a database. A scheduled event can remove sessions whose expiration time has passed.
CREATE EVENT cleanup_expired_sessions
ON SCHEDULE EVERY 30 MINUTE
DO
DELETE FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
Ensure that the application no longer requires expired session records before deleting them.
16.2 Daily Report Generation
A scheduled event can calculate daily totals and store them in a reporting table.
CREATE EVENT daily_sales_summary
ON SCHEDULE EVERY 1 DAY
DO
INSERT INTO sales_summary (summary_date, total_sales)
SELECT CURRENT_DATE, COALESCE(SUM(total_amount), 0)
FROM orders
WHERE order_date >= CURRENT_DATE
AND order_date < CURRENT_DATE + INTERVAL 1 DAY;
This example assumes the orders table contains order_date and total_amount columns. In a production system, add a unique constraint or another safeguard to prevent duplicate summaries for the same date.
16.3 Updating Expired Product Status
An online store can use a scheduled event to mark expired products as inactive.
CREATE EVENT update_expired_products
ON SCHEDULE EVERY 1 DAY
DO
UPDATE products
SET status = 'Inactive'
WHERE expiry_date < CURRENT_DATE
AND status <> 'Inactive';
16.4 Archiving Historical Data
Older records may need to be moved into an archive table to support reporting and maintenance.
CREATE EVENT archive_old_logs
ON SCHEDULE EVERY 1 MONTH
DO
BEGIN
INSERT INTO archived_logs (log_id, message, created_at)
SELECT log_id, message, created_at
FROM application_logs
WHERE created_at < CURRENT_TIMESTAMP - INTERVAL 6 MONTH;
DELETE FROM application_logs
WHERE created_at < CURRENT_TIMESTAMP - INTERVAL 6 MONTH;
END;
This example illustrates a possible archive workflow. In production, use a reliable transaction strategy, avoid duplicate archival, and ensure the archive table has compatible columns and constraints.
16.5 Periodic Status Updates
A scheduled event can update records when a time-based condition is satisfied.
CREATE EVENT expire_pending_orders
ON SCHEDULE EVERY 1 HOUR
DO
UPDATE orders
SET status = 'Expired'
WHERE status = 'Pending'
AND created_at < CURRENT_TIMESTAMP - INTERVAL 24 HOUR;
This event marks pending orders older than 24 hours as expired. Confirm that the rule matches the application's business requirements.
17. MySQL Events vs Triggers vs Stored Procedures
Although events, triggers, and stored procedures can all execute SQL statements, they are designed for different purposes.
| Feature |
Event |
Trigger |
Stored Procedure |
| Execution method |
Runs according to a schedule. |
Runs automatically when a specified table operation occurs. |
Usually runs when explicitly called. |
| Time-based scheduling |
Yes. |
No built-in time schedule. |
No built-in schedule. |
| Requires Event Scheduler |
Yes. |
No. |
No. |
| Can execute multiple SQL statements |
Yes, using compound statements. |
Yes, using compound statements. |
Yes. |
| Typical use |
Daily cleanup or scheduled reports. |
Audit a row insertion or deletion. |
Reusable business or database operations. |
18. Important Rules and Limitations
- The Event Scheduler must be enabled for events to execute.
- The event itself must be enabled.
- Creating an event requires the appropriate EVENT privilege on the target schema.
- The event's definer must have the required privileges for the SQL statements executed by the event.
- Events are associated with a schema and have names unique within that schema.
- One-time events use AT, while recurring events use EVERY.
- STARTS and ENDS can define the active period of a recurring event.
- Event schedule times are interpreted using the session time zone when the event is created or altered, and the event's time-zone context is retained for scheduling.
- Statements such as SELECT that only return a result set do not display that result to an interactive client when run by an event. Use INSERT ... SELECT or SELECT ... INTO when a result needs to be stored.
- An event may fail at execution time if its SQL action references missing tables, invalid columns, or insufficient privileges.
- Events do not accept direct input parameters in the same way as stored procedures, although an event can call a stored procedure.
- Long-running recurring events may overlap if one execution has not finished before the next scheduled execution becomes due.
- TRUNCATE TABLE and other operations should be used carefully when building automated cleanup tasks.
19. Event Scheduler Permissions and Security
MySQL events run using a security context associated with the event's definer. The account that creates or modifies an event must have the necessary privileges, and the definer needs the required permissions for the statements executed by the event.
19.1 Check the Current User
SELECT CURRENT_USER();
19.2 Understand the EVENT Privilege
The EVENT privilege controls operations such as creating, altering, and dropping scheduled events within a schema. Enabling the global Event Scheduler may require additional system-variable privileges.
19.3 Security Best Practices
- Use a dedicated database account for scheduled tasks when appropriate.
- Grant only the privileges required by the event's SQL action.
- Avoid granting unnecessary global administrative privileges.
- Review event definitions and their definers periodically.
- Protect tables that contain sensitive or financial information.
- Test scheduled DELETE and UPDATE statements before enabling them in production.
20. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Event does not execute |
The Event Scheduler is disabled. |
Check SHOW VARIABLES LIKE 'event_scheduler'. |
| Event is disabled |
The event status is DISABLED. |
Use ALTER EVENT event_name ENABLE. |
| CREATE EVENT fails |
Missing EVENT privilege or invalid SQL syntax. |
Check privileges and review the CREATE EVENT statement. |
| Event action fails |
The definer lacks permissions or referenced objects are invalid. |
Check table names, column names, and execution privileges. |
| One-time event disappears |
The event completed and was not configured to be preserved. |
Use ON COMPLETION PRESERVE if the definition should remain. |
| Event executes at an unexpected time |
The schedule was interpreted using a different session time zone than expected. |
Check the session time zone and the event's schedule. |
| Duplicate report rows appear |
The recurring event inserts the same summary more than once. |
Use appropriate unique constraints and idempotent SQL logic. |
| Event execution overlaps |
The previous run takes longer than the recurring interval. |
Optimize the task or implement a suitable locking mechanism. |
| Event cannot be enabled at runtime |
The scheduler is disabled at startup or the account lacks privileges. |
Review server configuration and the account's privileges. |
21. Best Practices for Using the MySQL Event Scheduler
21.1 Keep Event Actions Efficient
Write efficient SQL statements and ensure that frequently filtered columns are indexed when appropriate. A recurring event that scans or modifies a large table can affect database performance.
21.2 Test SQL Before Scheduling It
Run the event's UPDATE, INSERT, or DELETE statement manually in a development environment. Verify the rows affected before scheduling it for automatic execution.
21.3 Avoid Duplicate Processing
Design recurring events so that running the same task more than once does not create incorrect results. Use unique keys, status checks, and suitable transaction logic where necessary.
21.4 Use Appropriate Intervals
Choose a schedule based on the task's real requirements. A cleanup task that only needs to run daily should not necessarily run every few seconds.
21.5 Monitor Event Definitions
Use SHOW EVENTS and INFORMATION_SCHEMA.EVENTS to inspect schedules and enabled states. Maintain documentation for important events.
21.6 Handle Long-Running Tasks
If an event can take longer than its repeat interval, consider preventing simultaneous executions through a suitable locking or coordination strategy.
21.7 Review Time Zones
Make sure the event's schedule matches the intended time zone, especially when the database server and application users operate in different regions.
22. Practical Mini Project: Automated Expired Session Cleanup
Project Objective: Create a MySQL database task that automatically removes expired user sessions at regular intervals.
22.1 Create a Database
CREATE DATABASE session_cleanup_demo;
USE session_cleanup_demo;
22.2 Create a User Sessions Table
CREATE TABLE user_sessions (
session_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
session_token VARCHAR(255) NOT NULL,
expires_at DATETIME NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB;
22.3 Insert Sample Sessions
INSERT INTO user_sessions
(user_id, session_token, expires_at)
VALUES
(1, 'token_active_001', CURRENT_TIMESTAMP + INTERVAL 1 DAY),
(2, 'token_expired_002', CURRENT_TIMESTAMP - INTERVAL 1 DAY),
(3, 'token_expired_003', CURRENT_TIMESTAMP - INTERVAL 2 DAY);
22.4 Review Expired Sessions
SELECT *
FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
22.5 Create the Cleanup Event
CREATE EVENT cleanup_expired_user_sessions
ON SCHEDULE EVERY 1 MINUTE
DO
DELETE FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
This short interval is intended for a development demonstration. A production system should use a suitable cleanup frequency and should account for the application's session-retention requirements.
22.6 Verify the Event
SHOW EVENTS FROM session_cleanup_demo;
SELECT *
FROM user_sessions;
After the enabled event runs successfully, expired sessions should be removed while sessions with future expiration times remain.
22.7 Disable or Remove the Event
ALTER EVENT cleanup_expired_user_sessions DISABLE;
DROP EVENT IF EXISTS cleanup_expired_user_sessions;
Use DISABLE when you want to keep the event definition for later use. Use DROP EVENT when you no longer need the event.
23. Practice Exercises
- Create a one-time event that updates a status column after one hour.
- Create a recurring event that inserts a log record every five minutes.
- Create a daily event that updates expired product statuses.
- Create an event that starts tomorrow and ends after seven days.
- Create a daily sales summary event using INSERT ... SELECT.
- Display all events in the current database.
- Disable a recurring event and then enable it again.
- Change an event's schedule from every minute to every ten minutes.
- Create a one-time event that uses ON COMPLETION PRESERVE.
- Explain why an event may exist in the database but fail to execute.
24. Practice Exercise Solutions
24.1 One-Time Event After One Hour
CREATE EVENT update_status_after_one_hour
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
UPDATE system_settings
SET setting_value = 'Updated'
WHERE setting_name = 'status';
24.2 Log Every Five Minutes
CREATE EVENT five_minute_log
ON SCHEDULE EVERY 5 MINUTE
DO
INSERT INTO task_log (task_name, executed_at)
VALUES ('Five Minute Task', CURRENT_TIMESTAMP);
24.3 Update Expired Products Daily
CREATE EVENT daily_expired_product_update
ON SCHEDULE EVERY 1 DAY
DO
UPDATE products
SET status = 'Inactive'
WHERE expiry_date < CURRENT_DATE
AND status <> 'Inactive';
24.4 Display Events
SHOW EVENTS;
24.5 Disable and Re-enable an Event
ALTER EVENT five_minute_log DISABLE;
ALTER EVENT five_minute_log ENABLE;
These examples assume the relevant tables and columns exist. Create and test each event in a development database before using it in a production environment.
25. MySQL Event Scheduler Interview Questions and Answers
Q1. What is the MySQL Event Scheduler?
It is a MySQL server component that automatically executes scheduled SQL tasks.
Q2. What is a MySQL event?
A MySQL event is a named database object containing SQL statements that execute at a scheduled time or recurring interval.
Q3. What is the purpose of CREATE EVENT?
CREATE EVENT creates a scheduled database task with a defined schedule and SQL action.
Q4. What is the difference between AT and EVERY?
AT defines a one-time execution, while EVERY defines a recurring schedule.
Q5. What are STARTS and ENDS used for?
STARTS defines when a recurring event begins, and ENDS defines when the recurring schedule stops.
Q6. How can you check whether the Event Scheduler is enabled?
Use SHOW VARIABLES LIKE 'event_scheduler';.
Q7. How do you enable the Event Scheduler?
When permitted by the server configuration and privileges, use SET GLOBAL event_scheduler = ON;.
Q8. What does the DO clause specify?
The DO clause contains the SQL statement or compound statement that the event executes.
Q9. What is the purpose of ALTER EVENT?
ALTER EVENT modifies an existing event's schedule, action, or enabled status.
Q10. How can you list scheduled events?
Use SHOW EVENTS; in the selected database.
Q11. What is ON COMPLETION PRESERVE?
It retains a one-time event's definition after its schedule expires.
Q12. Can an event execute multiple SQL statements?
Yes. Use a compound statement with BEGIN and END.
Q13. What is the difference between a trigger and an event?
A trigger executes in response to a table operation, while an event executes according to a time-based schedule.
Q14. Why might an event fail even though it was created successfully?
The event's SQL action may reference missing objects, contain runtime errors, or lack the required privileges.
Q15. How do you remove a scheduled event?
Use DROP EVENT IF EXISTS event_name;.
26. Quick Revision Notes
- Event Scheduler: MySQL component that manages scheduled tasks.
- Event: A named database object containing a scheduled SQL action.
- CREATE EVENT: Creates a scheduled task.
- ON SCHEDULE AT: Defines a one-time event.
- ON SCHEDULE EVERY: Defines a recurring event.
- STARTS: Defines the start of a recurring schedule.
- ENDS: Defines the end of a recurring schedule.
- DO: Defines the SQL action.
- ALTER EVENT: Modifies an existing event.
- SHOW EVENTS: Lists scheduled events.
- ON COMPLETION PRESERVE: Retains an event definition after completion.
- DROP EVENT: Removes a scheduled event.
- event_scheduler: System variable used to check or control scheduler availability.
27. Conclusion
The MySQL Event Scheduler is a useful feature for automating repetitive database tasks. It can execute SQL statements once at a specified time or repeatedly at regular intervals. By using CREATE EVENT, ON SCHEDULE, AT, EVERY, STARTS, and ENDS, developers can automate cleanup, reporting, status updates, and other database maintenance operations.
For reliable scheduled tasks, ensure that the Event Scheduler is enabled, the event has the correct status and permissions, and the SQL action is tested carefully. Pay particular attention to time zones, duplicate processing, long-running operations, and the consequences of automated UPDATE and DELETE statements.
Continue Learning: Explore more database concepts through the MySQL Training Course. You can also visit the Course Demo Registration Page to learn more about the training.