Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time interval in mysql

is there a query for me to get the time interval - One minute, five minutes, quarter hour, half hour, hour, and day? I use MySQL as a database.

like image 599
hearmeroar Avatar asked Nov 13 '13 22:11

hearmeroar


People also ask

How does MySQL calculate time intervals?

The TIMEDIFF() function returns the difference between two time/datetime expressions. Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.

What is interval in MySQL?

MySQL INTERVAL() function returns the index of the argument that is more than the first argument. Syntax: INTERVAL(N,N1,N2,N3,...) It returns 0 if 1st number is less than the 2nd number and 1 if 1st number is less than the 3rd number and so on or -1 if 1st number is NULL. All arguments are treated as an integer.

How do you calculate intervals in SQL?

rn = t2. rn+1 -- previous and current row where t2. rn <= 3 -- last three rows group by t2.

How can I calculate hours between two dates in MySQL?

TIMEDIFF() function MySQL TIMEDIFF() returns the differences between two time or datetime expressions. It is to be noted that two expressions must be the same type. A datetime value.


2 Answers

You are probably looking for date_sub:

SELECT * FROM YOURTABLE t
WHERE t.timestamp > date_sub(NOW(), interval 1 hour);

For different intervals you can change the 1 hour to 5 days, 5 weeks, etc).

From the documentation:

DATE_SUB(date,INTERVAL expr unit)

The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

The following table shows the expected form of the expr argument for each unit value.

unit Value     Expected expr Format

MICROSECOND    MICROSECONDS
SECOND         SECONDS
MINUTE         MINUTES
HOUR           HOURS
DAY            DAYS
WEEK           WEEKS
MONTH          MONTHS
QUARTER        QUARTERS
YEAR           YEARS
like image 128
Filipe Silva Avatar answered Oct 12 '22 00:10

Filipe Silva


to get a range, like from 30 to 45 minutes ago, do like this

SELECT * FROM tbl 
WHERE tbl.mydate > DATE(DATE_sub(NOW(), INTERVAL 45 MINUTE)) 
AND tbl.mydate < DATE(DATE_sub(NOW(), INTERVAL 30 MINUTE));
like image 23
AwokeKnowing Avatar answered Oct 12 '22 00:10

AwokeKnowing