Skip to content
Advertisement

Change column value if date is older than 1 hour in mysql/mariadb?

Say I have below SQL table:

+------------+---------------------+
|  Status    |   Date              |
 ------------+---------------------+
|  Available | 2020-12-19 18:03:42 |
+------------+---------------------+

Basically I want MySQL to check the Date column every 3 minutes and if Date value is older than 1 hour, I want to change Status to Offline. Can we achieve such thing in SQL? Alternatively if there is easier solution in Django python, I am open to use that as well.

Advertisement

Answer

I would recommend doing this with a view:

create view v_t as
    select (case when date + interval 1 hour < current_timestamp then 'Offline'
                 else status
            end) as status,
           . . .   -- whatever other columns you have here
    from t;

A view has the following advantages:

  • The value is automatically correct. Users of the view will see the 'Offline' status exactly after an hour.
  • There is no overhead on changing the data.
  • This works even if the entire system goes down and then comes back up.

You can actually set the status at your leisure — say a job that runs once per day or per week at an off-time.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement