CREATE EVENT lets MySQL run SQL statements automatically on a defined schedule, eliminating external cron jobs.
Run SET GLOBAL event_scheduler = ON;
as a privileged user or start the server with --event-scheduler=ON
. Persist the setting in my.cnf
for reboots. Verify with SELECT @@event_scheduler;
.
Grant the EVENT
privilege: GRANT EVENT ON *.* TO 'analyst'@'%';
. Without it, CREATE EVENT
and ALTER EVENT
fail.
CREATE EVENT [IF NOT EXISTS] name ON SCHEDULE schedule DO statement;
. The schedule can be AT
a timestamp or EVERY
interval, with optional STARTS
/ ENDS
.
The event below inserts yesterday’s revenue into order_summaries
every night at 00:05.
CREATE EVENT IF NOT EXISTS ev_daily_revenue
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_DATE + INTERVAL 5 MINUTE
DO
INSERT INTO order_summaries(report_date,total_revenue)
SELECT CURRENT_DATE - INTERVAL 1 DAY,
SUM(total_amount)
FROM Orders
WHERE order_date = CURRENT_DATE - INTERVAL 1 DAY;
Change the frequency: ALTER EVENT ev_daily_revenue ON SCHEDULE EVERY 1 HOUR;
. Pause execution: ALTER EVENT ev_daily_revenue DISABLE;
. Remove permanently with DROP EVENT ev_daily_revenue;
.
Name events descriptively, wrap complex logic in stored procedures, store definitions in version control, log results to a table, and test schedules in staging first.
Events are written to the binary log, so they replicate by default. Use ALTER EVENT ... DISABLE ON SLAVE
to stop execution on replicas.
Yes. Place the logic in a stored procedure and call that procedure from DO CALL proc_name();
.
Query information_schema.EVENTS
or run SHOW EVENTS FROM database_name;
.