Create an Event to Update Data Periodically
In this step, we will create a MySQL event that updates a table periodically. First, we need to create a database and a table. Then, we will create the event to update the table every minute.
First, let's connect to the MySQL server using the mysql
client. Open a terminal and execute the following command:
mysql -u root -p
Enter the root password when prompted.
Now, let's create a database named test_db
:
CREATE DATABASE IF NOT EXISTS test_db;
Next, switch to the test_db
database:
USE test_db;
Now, let's create a table named event_table
with two columns: id
(INT, primary key, auto-increment) and value
(INT):
CREATE TABLE IF NOT EXISTS event_table (
id INT AUTO_INCREMENT PRIMARY KEY,
value INT
);
Let's insert an initial value into the table:
INSERT INTO event_table (value) VALUES (0);
Now, let's create the event. The event will update the value
column in the event_table
table every minute. Execute the following SQL statement:
CREATE EVENT IF NOT EXISTS update_event
ON SCHEDULE EVERY 1 MINUTE
DO
UPDATE event_table SET value = value + 1;
This statement creates an event named update_event
. The ON SCHEDULE EVERY 1 MINUTE
clause specifies that the event should run every minute. The DO
clause specifies the SQL statement to execute when the event runs, which increments the value
column by 1.
To check if the event is created, execute the following SQL query:
SHOW EVENTS FROM test_db;
You should see output similar to this:
+----------+---------------+-------------+-----------+----------+---------------------+---------------------+-----------+------------+-------------------+----------------------+--------------------+--------------------+
| Db | Name | Definer | Time zone | Type | Execute at | Interval_value | Interval_field | Starts | Ends | Status | Originator | character_set_client | collation_connection | db_collation |
+----------+---------------+-------------+-----------+----------+---------------------+---------------------+-----------+------------+-------------------+----------------------+--------------------+--------------------+
| test_db | update_event | root@% | SYSTEM | RECURRING | NULL | 1 | MINUTE | 2024-10-27 14:30:00 | NULL | ENABLED | 1 | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
+----------+---------------+-------------+-----------+----------+---------------------+---------------------+-----------+------------+-------------------+----------------------+--------------------+--------------------+
1 row in set (0.00 sec)
This confirms that the event has been created and is enabled.
Now, exit the MySQL client:
exit
The event will now run every minute, updating the value
column in the event_table
table. In the next step, we will check the execution status of the event.