I have a simple table that has a TIME column named timeC in the example below. I want to select all the records for which timeC is in the last five minutes. I have tried the following and many variations without success.
SELECT * FROM sample_schema.`exampleTable`
WHERE MINUTE(TIMEDIFF(SELECT TIME(NOW())), `timeC`)<5;
Note that the column is TIME, not DATETIME or TIMESTAMP.
Suggestions?
Your parentheses are in the wrong places. So you're calling TIMEDIFF() with 1 argument, and calling MINUTE() with 2 arguments. Also, you don't need to use SELECT to get TIME(NOW()), you can just use that function call as an argument.
SELECT *
FROM exampleTable
WHERE MINUTE(TIMEDIFF(TIME(NOW()), timeC)) < 5
However, there's still a problem with this. TIMEDIFF() can return a negative time if timeC is later in the day, but MINUTE() always returns the positive value of the minute, so this will match anything from 5 minutes ago to 5 minutes later. It would be better to simply compare the time with a range:
SELECT *
FROM exampleTable
WHERE timeC BETWEEN TIME(DATE_SUB(NOW(), INTERVAL 5 MINUTE)) AND TIME(NOW())
There's one ramaining problem. If you perform this query shortly after midnight, the time of 5 minutes earlier will be a late time from the previous day. For instance, if it's currently 00:02, 5 minutes earlier will be 23:57, and nothing will match the BETWEEN expression. You need to check for that:
SELECT *
FROM exampleTable
WHERE CASE
WHEN TIME(NOW()) >= '00:05'
THEN timeC BETWEEN TIME(DATE_SUB(NOW(), INTERVAL 5 MINUTE)) AND TIME(NOW())
ELSE timeC BETWEEN '00:00' AND TIME(NOW())
OR
timeC BETWEEN TIME(DATE_SUB(NOW(), INTERVAL 5 MINUTE)) AND '23:59:59'
END
Related
Hello I am attempting to pull the last 5 minutes of data from the database.
The query I have written below is not pulling the data I need.
Select e.*
from Event e
where e.whenoccurred >= datefunc('10/01/2019 00:00 -05:00', '-5 minutes')
and dateadd(minutes,-5,getdate())
I receive the error
Query has failed: no such column: minutes
Any ideas that can help?
SysDate
returns the current date and time set for the operating system on which the database resides. The datatype of the returned value is DATE, and the format returned depends on the value of the NLS_DATE_FORMAT initialization parameter. The function requires no arguments. In distributed SQL statements, this function returns the date and time set for the operating system of your local database.
this query get sysdate minus five minutes.
select *
from event
where whenoccured >= sysdate - (5/1440)
Use
Query #1 Demo
SELECT * FROM event
where whenoccured >= date_sub(now(), interval 5 minute);
Query #2 Demo
SELECT * FROM event
WHERE whenoccured >= NOW() - INTERVAL 5 MINUTE;
Query #3 Demo
SELECT * FROM event
WHERE DATE_ADD(whenoccured , INTERVAL 5 MINUTE) >= NOW();
You can use
select *
from event
where whenoccured >= systimestamp - interval '5' minute
where systimestamp stands to return the current system date, including fractional seconds and time zone.
Update (if MySQL DB is the case instead of Oracle initially as tagged) use date_sub() function:
select *
from event
where whenoccured >= date_sub(now(), interval 5 minute);
assuming whenoccured column is of type datetime or timestamp
Demo
On SQL Server, the first parameter of dateadd function should written in singular. In your case, instead of "minutes" you should use "minute".
Here's a working example:
select getdate()
select dateadd(minute,-5,getdate())
For further details on dateadd function I would suggest you to refer to https://www.w3schools.com/sql/func_sqlserver_dateadd.asp
I have a table which contains multiple data on same time interval for every minute. I want to aggregate data of every 5th minute in last 10 mins. I have tried all the solution provided on stack overflow but its not getting accurate data for me as none of them has tried to get data for fix interval of time.
I am using this query :
SELECT ROUND(unix_timestamp(footable.createdTime)/(60 * 5)) AS timekey, avg(mainData) as aggData
FROM footable
WHERE footable.createdTime > date_sub(now(), INTERVAL 10 MINUTE)
GROUP BY timekey
It should return max 2 records everytime but most of the time it returning 3 records.
Note:- table contains data for every minute its confirmed and this is test condition for 10 mins it could be a data of last hour. Its not a duplicate question read the description carefully.
Any help will be appreciated..!!
I figured it out myself and below is the query to solve the issue :
SET #timeStmp := UNIX_TIMESTAMP(date_sub(now(), INTERVAL 10 MINUTES));
SELECT #timeStmp := IF(((unix_timestamp(footable.createdTime) - #timeStmp) >= 295), unix_timestamp(footable.createdTime),#timeStmp) as timekey, avg(mainData) as aggData
FROM footable
WHERE footable.createdTime > date_sub(now(), INTERVAL 10 MINUTE)
GROUP BY timekey
This query will give exact minute to minute interval aggregated data on every execution. Enjoy..!!
I have a requirement of counting the no. of records inserted into a table for every half an hour.say from 11 to 11 30 if there 5 records and 11 30 to 12 if there are 4 records how to find the no. of records
You'd need the datetime each row was inserted; it's easiest if that is a column in the table. (We'll assume here that the column is named inserted_dt.)
All that we really need is an expression that operates on inserted_dt to return a single value for every value within a given half hour.
If we needed "hour" intervals, and not "half-hour" intervals, it would be very easy:
DATE_FORMAT(t.inserted_dt,'%Y-%m-%d %H:00:00')
Let's define the first "half-hour" ranges as minutes >= '00' AND minutes < '30'
To get the "minutes" out of the inserted_dt column, we could use either of
EXTRACT(MINUTE FROM t.inserted_dt)
DATE_FORMAT(t.inserted_dt,'%i')
We can use a conditional test to determine whether the minutes value is less than 30, or flip it around and test for greater than or equal to thirty:
DATE_FORMAT(t.inserted_dt,'%i')+0 >= 30
We can put that back together with the "year-month-day-hour", by adding an interval of either 0 or 30 minutes,
DATE_FORMAT(t.inserted_dt,'%Y-%m-%d %H:00:00')
+ INTERVAL 30*(DATE_FORMAT(t.inserted_dt,'%i')+0>=30) MINUTE
(There are lots of expressions we could use to do something similar; this one is just one of the shortest we can use to return a DATETIME datatype
Now, we just add the expression to the SELECT list of our query, we get a value that identifies the "halfhour".
To get a "count" for each half hour range, that's just a simple COUNT() aggregate and a GROUP BY. The "trick" is that we use the new "halfhour" expression in the GROUP BY clause.
SELECT DATE_FORMAT(t.inserted_dt,'%Y-%m-%d %H:00:00')
+ INTERVAL 30*(DATE_FORMAT(t.inserted_dt,'%i')+0>=30) MINUTE AS halfhour
, COUNT(*)
FROM mytable t
GROUP BY halfhour
Obviously, add a WHERE clause if you only want to return results for a specified datetime range,
SELECT DATE_FORMAT(t.inserted_dt,'%Y-%m-%d %H:00:00')
+ INTERVAL 30*(DATE_FORMAT(t.inserted_dt,'%i')+0>=30) MINUTE AS halfhour
, COUNT(*)
FROM mytable t
WHERE t.inserted_dt >= '2014-08-12'
AND t.inserted_dt < '2014-08-12' + INTERVAL 1 DAY
GROUP BY halfhour
I'm trying to get an mysql query similar to date_trunc in psql.
Unfortunate Mysql do not have date_trunc function and I found I can use extract instead in Mysql.
What I want to do is write a script which i will run let say 10 minutes past each hour but I want to only select data from begin of an hour till end of this hour.
For example I will run script 12:10 and I want to display data from 11:00:00 till 11:59:59.
In PSQL query would look like that:
SELECT *
FROM data
WHERE time > ( date_trunc('hour',now()) - interval '1 hour' )
AND time <= ( date_trunc('hour',now()) ) ORDER BY time;
I was trying to use extract in similar fashion but I have no rows returned or error :/
Query below returns for example some narrowed data but it's like 2 hours each day from day one when database was started not last hour only:
SELECT *
FROM data
WHERE extract(hour from cr_date) between extract(hour from now()) - interval 1 hour)
AND extract(hour from now())
ORDER BY cr_date;
Any ideas how this can be achieved? or what I'm doing wrong in this query?
Hour is only an integer, so it's finding any matches between , for example, 9 and 10, regardless of the date.
I would recommend
select * FROM data
where cr_date >= date(now()) + INTERVAL hour(now())-1 HOUR
and cr_date <= date(now()) + INTERVAL hour(now()) HOUR
date(now()) returns midnight, and hour(now()) returns the number of hours since midnight
so, at 11:10 am, it should result in a results between midnight + 10 hours (10 am) and midnight + 11 hours (11 am)
I am trying to write up a query that will give me the time since the last post in seconds, something along the lines of
SELECT (NOW() - mydatetime) as val1 FROM posts ORDER BY mydatetime DESC LIMIT 1
How do I get val1 in seconds?
Since you are only interested in seconds, you can simply subtract the two dates as timestamps:
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(mydatetime) FROM ...
Note: MySQL has a set of Date Time Functions, I encourage you to browse through them.
TIMESTAMPDIFF(SECOND, mydatetime, NOW())