Need to Select DateTime Range in MySQL - mysql

I have a txn (transaction) table which has a datetime field named post_ts, which is the field that represents the date of the transaction.
I am writing the code for a batch job (which is supposed to be a weekly job to be run on Sundays) using Spring Batch, and I need to run the query such that I need to fetch all transactions from a week back to the date I am running the job.
Apart from other million business rules to be applied to the query, I need the transactions from (currentdate) to (current date - 7)

You can user mysql DATEDIFF function to achieve this :
SELECT *
FROM txn
WHERE DATEDIFF( CURDATE( ) , `post_ts` ) <= 7;

If you don't need more precision that the date part (no hours, minutes nor seconds to be taken into account), then you can use the function DATEDIFF:
SELECT *
FROM txn
WHERE DATEDIFF( NOW(), post_ts ) <= 7;
EDIT: I've changed the answer. It was mistaken, as I first used the TIMEDIFF function instead of DATEDIFF.
TIMEDIFF gives the difference in hours, minutes, ... whereas DATEDIFF gives the difference in the date part, ignoring the hour:minutes:seconds part.

select
*
from
txn
where
TO_DAYS(NOW()) - TO_DAYS(post_ts) <= 7;

Related

Sql -How to fetch the last 5 minutes of data

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

MySQL select entries from last hour based on epoch field

I need to return all the entries in a MySQL database from the last hour. The database has a column named time that has epoch values in.
This bit of psuedo code is what I want to be able to achieve but am not sure how to do this in MySQL. In another language I'd check to see that the epoch value of time in each row is no more than 3,600 different.
SELECT * FROM dailyltc WHERE `time` <= 1 hour
Not using functions to convert your stored epoch value enables MySQL the use of an index. Because of that I prefer the calculate the limits with UNIX_TIMESTAMP instead of converting the stored value to a DATETIME value.
SELECT
*
FROM
dailyltc
WHERE
`time` > UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR);
Should newer values exist then you can simply add the upper bound:
SELECT
*
FROM
dailyltc
WHERE
`time` > UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR)
AND
`time` <= UNIX_TIMESTAMP(NOW());

Calculate difference between dates

The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1

Mysql: how to reuse a calculation within a query

I have a query below that I use to retrieve the records not updated for a given time (in hours) and order it by elapsed time:
SELECT TABLE.Key, TIMESTAMPDIFF(HOUR, TABLE.Date_last_consulted, CURRENT_TIMESTAMP)
FROM TABLE WHERE TIMESTAMPDIFF(HOUR, TABLE.Date_last_consulted,
CURRENT_TIMESTAMP) <= 7 ORDER BY TIMESTAMPDIFF(HOUR, TABLE.Date_last_consulted,
CURRENT_TIMESTAMP);
As you can see, it calls multiple times TIMESTAMPDIFF, which is not very efficient as all these calls lead to useless SQL calculations.
I was wondering if there were a way to reuse the calculations so it is processed only once?
Thanks a lot for your help.
Florent
SELECT
t.Key, t.dif
FROM (
SELECT key, TIMESTAMPDIFF(HOUR, TABLE.Date_last_consulted, CURRENT_TIMESTAMP) dif
FROM TABLE
) t
WHERE
t.dif <= 7
ORDER BY
t.dif

Is there anyway to do math on a MySQL query?

I have two fields, one with the purchase date and one with the lifespan of an item. I am wondering if there is any way to determine if the current date is past the lifespan. So, pretty much if MySQL could test if current_date is > purchase_date + lifespan.
The purchase date is a date formated yyyy-mm-dd and lifespan is an integer of months. Is there any way to perform this calculation?
You might try:
SELECT * FROM table WHERE NOW() > (purchase_date + INTERVAL lifespan MONTH)
But you might use
SELECT * FROM table WHERE NOW() > date_add(purchase_date, INTERVAL lifespan MONTH)
Or DATEDIFF
SELECT * FROM table WHERE DATEDIFF(NOW(), purchase_date) / 30 < lifespan
How about using DATEDIFF?
Your query would be something along these lines:
SELECT * FROM table WHERE DATEDIFF(NOW(), purchase_date) < lifespan
Forgive me if my syntax is a little off, I don't have an SQL instance to test on right now
Yes it is possible, using the MySQL date and time functions.