In MySQL we can use the CREATE EVENT
statement to create scheduled events. As with many CREATE ...
statements, we have the option of using the IF NOT EXISTS
clause to specify that the object should only be created if it doesn’t already exist.
Of course, we wouldn’t normally be trying to create an event if we know that it already exists. But there may be times where we’re not sure, and we want our code to handle this scenario without throwing an error if an event with the same name already exists. This is common when creating scripts that are designed to be run across multiple environments. That’s where the IF NOT EXISTS
clause can come in handy.
Example
Here’s an example of code that creates an event only if there’s not already an event with the same name:
CREATE EVENT IF NOT EXISTS Event1
ON SCHEDULE
EVERY 1 MINUTE
DO
INSERT INTO EventTest ( EventTimestamp, InsertedBy )
VALUES (NOW(), 'Event1');
We can run that code multiple times without error. If the event doesn’t exist, it will be created. If it does exist, it won’t throw an error, but a warning will be issued.
Here’s what that might look like:
Query OK, 0 rows affected, 1 warning (0.00 sec)
We can view the warning like this:
SHOW WARNINGS;
Output:
+-------+------+-------------------------------+ | Level | Code | Message | +-------+------+-------------------------------+ | Note | 1537 | Event 'Event1' already exists | +-------+------+-------------------------------+
As suspected, the event already exists.
Manually Check the Event
We can also check for the existence of an event by running a query. For example, we can run SHOW EVENTS
or query the information_schema.events
table for an event of the same name:
Here’s an example of querying the information_schema.events
table:
SELECT event_name
FROM information_schema.events
WHERE event_name = 'Event1';
Result:
+------------+ | EVENT_NAME | +------------+ | Event1 | +------------+
In this case I narrowed the results to just those events that are called Event1
.