How do I subtract using SQL in MYSQL between two date time values and retrieve the result in minutes or second?

There are functions TIMEDIFF(expr1,expr2), which returns the value of expr1-expr2, and TIME_TO_SEC(expr3), which expresses expr1 in seconds.

Note that expr1 and expr2 are datetime values, and expr3 is a time value only.

Check this link for more info.


TIMESTAMPDIFF is like TIMEDIFF which Matthew states, except it returns the difference of the two datetimes in whatever units you desire (seconds, minutes, hours, etc).

For example,

SELECT TIMESTAMPDIFF(MINUTE,LogOutTime,LogInTime) AS TimeLoggedIn
FROM LogTable

Would return the number of minutes the user was logged in (assuming you stored this kind of thing in a table like that).


I would do it like this - fetch where last activity is within 10 mins of now

SELECT * FROM table WHERE last_activity >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)

Tags:

Mysql

Sql

Date