简体   繁体   中英

Oracle: how to update “outdated” date in table?

Our use case :

For table USERS :

update all rows (set value 'N' for column ACTIVE ) in case when user was inactive (column 'LAST_VISIT' ) more that 60 minutes.

Google helped me to find how to obtain current time in db (I use Oracle ):

SELECT sysdate FROM dual;

Then I found the way how to find the difference in minutes between two dates:

SELECT(date1 - date2)*1440

Looks like a little bit ugly... but ok.

Now, I am trying to combine all together:

UPDATE USERS u 
SET ACTIVE='N' 
WHERE  SELECT((SELECT sysdate FROM dual) - u.LAST_VISIT)*1440 >60;

Could you please review my final query.

Is it ok? Or, maybe, it is possible to optimize it?

You can simplify the query

UPDATE users u
   SET active = 'N'
 WHERE u.last_visit < sysdate - interval '1' hour;

If there is an index on last_visit that can be used for the query (because the predicate is sufficiently selective), this query can potentially use that index.

Justin's answer is very good, but it will probably update too many rows. You should add an extra condition to the where clause:

UPDATE users u
   SET active = 'N'
    WHERE active <> 'N' AND u.last_visit < sysdate - interval '1' hour;

This saves the attempted update for users who are already inactive. (Note: this version assumes that active does not take the value of NULL .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM