MySQL DATE_ADD() not working - mysql

In my database I have a table containing some business offers. One of the columns is expire, which contains the date a certain offer expires.
I want to select all offers which expire in 10 days. Here is my code:
SELECT * FROM offers WHERE TIME_ADD(NOW(), INTERVAL 10 DAYS) = expire;
I want to select all columns from offers, where the expiry date is equal date now plus 10 days (so they expire in 10 days). MySQL doesn't let me do that, it marks "=expire" as an error
Syntax error unexpected 'expire' (expire).
Why is that? ( I'm working on MySQL workbench btw)

If you want to find all offers that expire in 10 days, but you're not concerned as to what time in 10 days that they expire, then you can use the following:
SELECT *
FROM offers
WHERE DATE(expire) = DATE_ADD(CURRENT_DATE(), INTERVAL 10 DAYS);
If however you want to find all offers that expire in 10 days, to the exact second, then you can use the following instead:
SELECT *
FROM offers
WHERE expire = DATE_ADD(NOW(), INTERVAL 10 DAYS);
Notice how the first query uses CURRENT_DATE(), which will return only a date value - 2018-08-03. Whereas the second query uses NOW(), which will return a datetime value - 2018-08-03 08:29:00.

replace INTERVAL 10 DAYS with INTERVAL 10 DAY

Related

Data from current date to 30 days after current days

Why this query is not working
SELECT * FROM history WHERE DATE(date) < CURDATE() + 30
I am trying to get the data from 30 days but my query is not working.Why
What does +30 mean? Days? Years? Months? Hours? You need to use (the proper syntax) a format MySQL understands:
SELECT * FROM history WHERE DATE(date) < CURDATE() + INTERVAL 30 DAY
To get the data from today on to 30 days after current day, you've got to set an upper and an lower limit, so use:
SELECT * FROM history WHERE
date >= CURDATE()
AND
date < CURDATE() + INTERVAL 31 DAY
Please note that by not using a function on your date column you won't prohibit MySQL to use an index on this column.
The lower limit should be obvious, the upper limit means that you've got the complete day that's 30 days later than today. If you use + INTERVAL 30 DAY instead this last day is excluded from the result.
Because you're not using the right construct, try:
SELECT * FROM history WHERE DATE_ADD(date, INTERVAL 30 DAY);

Mysql time range query using extract

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)

Logic for dates in sql query for mysql

Hi i am totally confused with a date logic in my mysql query for a cron job to be run everyday at 12:00 AM
I am working on a auto listing website where the car listings are having a expiry date in mysql datetime format.
All the expired listings will be deleted from the website after 7 days from the datetime of the expiry
When the cron job will run it has do following things
Task 1 - Send an email alert to the users telling them that their listing has expired.
So I need to select all those listings which have expired since last time the cron job has been run and not include listings before that in order to send the expiry alert email only once per listing.
I tried following sql query for this task (Again confused with this as well)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 1 DAY) AND expiry_date < NOW()
Task 2 - Will send an email alert to users telling them that listing is going to be permanently deleted after 24 hours.
So I need to select all those listings which are going to be deleted in more than 24 hours / 6 days have passed since they were expired and i need to make sure that they get minimum 24 hours time to renew them. Also i need to select / build the sql query in such a way that only those listings get selected which are going to expiry in 1 days and not other in order to avoid multiple email alerts instead of one time email alert
I tried following sql query for this task (I am totally confused with this query)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 7 DAY) AND expiry_date < DATE_SUB(NOW(), INTERVAL 1 DAY)
Task 3 - Delete all the listings which were expired more than 7 days ago
I tried following sql query for this task
SELECT car_id FROM cars WHERE expiry_date < DATE_SUB(NOW(), INTERVAL 7 DAY)
Please help me in perfecting all the 3 queries so that the cron does it job exactly as i want. Also please let me where it has to >= (greater than or equal to) or <= (less than or equal to)
Here is the sqlfiddle table structure and couple of records (though they are not expired yet)
http://sqlfiddle.com/#!2/cfcdf
I will really appreciate the help.
Is this what you are looking for? Please try to add another column to see the differnce between expiry_date and current date time for you to get a better idea of the dates you are dealing with. Please look into some dates functions in MYSQL.
SQLFIDDLE DEMO
-- 3rd query expiry dates older than 7 days from
-- today
SELECT car_id, expiry_Date,
DATE_sub(NOW(), INTERVAL 7 DAY)
FROM cars
WHERE expiry_date <=
DATE_sub(NOW(), INTERVAL 7 DAY)
;
-- same
SELECT car_id, expiry_Date,
DATE_ADD(NOW(), INTERVAL -7 DAY)
FROM cars
WHERE expiry_date <=
DATE_ADD(NOW(), INTERVAL -7 DAY)
;
-- 2nd query going to expire in exactly 1 day
SELECT car_id, expiry_date,
Now() + interval 1 day
FROM cars
WHERE expiry_Date = Now() + interval 1 day
;
-- 1st query: expired
SELECT car_id FROM cars
WHERE expiry_date < Now()
;
-- 1st query: expired last 24 hours
SELECT car_id,DATEDIFF(expiry_date, Now())
FROM cars
WHERE expiry_Date < Now()
AND expiry_Date >= Now() - interval 1 day
;
Check out these queries
select * from cars where datediff(EXPIRY_DATE,now())=-1;
select * from cars where
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now())>=1 and
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now()) <=2;
select * from cars where datediff(expiry_date,now())<=-7;
ope they are working according to your need.
fiddle http://sqlfiddle.com/#!2/785ea/5
There is nothing significantly wrong with your queries, if you do not understand the functions that you have used then google them and read about them until you do.
There is a fundamental problem in your approach in that it relies on the cron job being run at exactly 24 hour intevals - to the milisecond - or there will be double ups and/or omissions.
You need another table to store details of when your batch program last ran; intitialise this with 1 row with a date a long time in the past so that we have a starting point.
You can get the most recent batch by SELECT MAX(date_ran) FROM BatchRecordTables. Store this in a local variable T0. Get the current time, store this in a local variable T1 (Do not use NOW() in multiple queries as they will be slightly differant times and you need them to be the same). I do not know the syntax for this is MySQL - you will have to look it up.
Your situations then become.
Send email to people whose listings have expired since that last time the cron job was run i.e. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN T0 AND T1. This will only select people whoose listings have expired between this batch and the previous one.
For the second case, we need to know that these people have got the first email i.e. that their listing had expired before the last batch run so SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 6 DAY) AND T0. This will only select people whoose listings expired before the last batch (i.e. they got the exprired email) and more than 6 days ago.
Same logi applies - we want to know they got the second email. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 7 DAY) AND DATE_SUB(T0, INTERVAL 6 DAY)
May I also suggest that you do not permenantly delete the listings but either copy them to a DeletedListings table or Flag them with a Deleted column - each has its own pros and cons. In the information age, never throw data away - you never know when it might be valuable.

How to Subtract Days in MySQL

How can I subtract time in MySQL? For example, today is 16 March; I want to subtract 15 days to reach 1 March. Are there any methods that can be used to subtract 15 days from the current date?
SELECT DATE(NOW()-INTERVAL 15 DAY)
For a list of units see http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
Not entirely related to this question but is related to the title:
SELECT SUBTIME("10:24:21", "5"); -- subtracts 5 seconds. (returns "10:24:16")
SELECT SUBTIME("10:24:21", "01:00:00"); -- subtracts one hour. (returns "09:24:21")
Documentation: MySQL SUBTIME function
Use:
SELECT NOW() - INTERVAL 15 DAY
to keep the datetime precision.
You can use this :
SELECT DATE(NOW()-INTERVAL 15 DAY);
for when you want to subtract the number of days.
In order to subtract the time instead, say 15 minutes, the following should work:
SELECT(DATE_SUB(NOW(), INTERVAL '15:0' MINUTE_SECOND));
Adding the reference link again :- https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add.
Yes its possible using date function in Mysql
select distinct
lastname,
changedat, date_add(changedat, interval -15 day) as newdate
from employee_audit;
lastname and changedat is field name and employee_audit is table name.
I have subtract 15 days from my date - check image please. thanks

How to do a query (limit between 2 ages - stored as date)

I have a table where it stores the users.
And i want a query to find the users which are between eg 25 years old and 31 years old.
The age is stored at the mysql table as date (it stores the birthday).
(eg: 1980-02-25 (yyyy-mm-dd))
How the query should be written in order to find each time the people who are between two given ages?
Thanks.
You can either compute the necessary date range in your backend code, or in MySQL itself. Should you choose MySQL, here's what the query might look like:
SELECT user.* FROM user
WHERE birthdate >= DATE_SUB(NOW(), INTERVAL 31 YEAR)
AND birthdate <= DATE_SUB(NOW(), INTERVAL 25 YEAR)
There is also the somewhat shorter BETWEEN clause for MySQL. I'd recommend CURDATE() instead of NOW() because it does not have the time component.
SELECT * FROM user
WHERE birthdate
BETWEEN
(CURDATE() - INTERVAL 31 YEAR)
AND
(CURDATE() - INTERVAL 25 YEAR)
Note: it's inclusive.