Records between NOW() and 3am today or yesterday - mysql

How can I get records in a table between NOW() and the previous 3am?
This would be easy if it's 9am, but how do I write this if it's 2am? i.e I want the trades between DATE_SUB(CURDATE(), INTERVAL 21 HOURS) and NOW(). I'm looking for some code which can do both without needing to check the time in usercode and choose between two sql statements.
I'm sure there's a simple solution to this, but it's eluding me.

A simple idea is to subtract three hours and compare the date:
where date(date_sub(col, interval 3 hour)) = (case when hour(date) >= 3 then curdate() else date_sub(curdate(), interval 1 day)
Or, more explicitly, just do the comparison in SQL:
where (hour(date) >= 3 and date(col) = curdate()) or
(hour(date) < 3 and date(col) = date_sub(curdate(), interval 1 day)

I'll add my own answer (I finally gave up and explored using IF and found it could be used inside SELECT statements), but #Gordon Linoff might be better - I've no idea which of these is faster.
SELECT IF (NOW() > DATE_ADD(CURDATE(), INTERVAL 3 HOUR),
DATE_ADD(CURDATE(), INTERVAL 3 HOUR),
DATE_SUB(CURDATE(), INTERVAL 21 HOUR))
which can then be used as the conditional on an outer SELECT.

Related

MySQL How to select date field exactly 7 days before today and for time last 1 hour

I have a query that selects records created from 1 hour in past from current time.
select ts from <table_name> where ts >= DATE_SUB(NOW(), interval 1 hour);
I can also select date before 7 days using
select count(*) from <table_name> where ts >= DATE_SUB(NOW(), interval 7 day);
How can I use these two date features to get records before 7 days from today and time 1 hour in past from current time.
For example, if the present time is 2015-11-06 10:03:00 then how can I get data for time between 2015-10-30 09:03:00 to 2015-10-30 10:03:00
I tried something like this, but it gives syntax error:
select ts from <table_name> where ts >= DATE_SUB(DATE(NOW()), INTERVAL 7 DAY), interval 1 hour)
select ts from <table_name> where ts >= DATE_SUB(NOW(), INTERVAL 7 DAY), interval 1 hour)
Your examples have syntax errors (too many closing parentheses )). If you want to use DATE_SUB(), you need to use it twice. To get entries between one time and another, use WHERE ... BETWEEN ... AND ...
You can use this:
SELECT ts
FROM iv_split_skill_metrics
WHERE ts BETWEEN
DATE_SUB(
DATE_SUB(DATE(NOW()), INTERVAL 7 DAY),
interval 1 hour)
AND
DATE_SUB(DATE(NOW()), INTERVAL 7 DAY)
Or, even better, skip DATE_SUB() entirely and just do subtraction, like this:
SELECT ts
FROM iv_split_skill_metrics
WHERE ts BETWEEN NOW() - INTERVAL 7 DAY - INTERVAL 1 HOUR
AND NOW() - INTERVAL 7 DAY
Edit: For some reason, you edited your question after I posted this and replaced iv_split_skill_metrics with <table_name> in your question, but the examples above will work regardless. Just use the correct table and column names, of course!
Edit 2: I see now that you want entries between 7 days plus 1 hour ago and 7 days ago. I have tweaked my answer to show you how to do that.
Your goal is not 100% clear but just my attempt:
SELECT ts
FROM table_name
WHERE ts >= DATE_ADD(DATE_ADD(NOW(), INTERVAL -7 DAY), INTERVAL -1 HOUR)
AND ts <= DATE_ADD(NOW(), INTERVAL -7 DAY);
but form performance perspective this query would be much faster:
http://sqlfiddle.com/#!9/9edd1/2
SET #end = DATE_ADD(NOW(), INTERVAL -7 DAY);
SET #start = DATE_ADD(#end, INTERVAL -1 HOUR);
SELECT ts
FROM table_name
WHERE ts BETWEEN #start AND #end;

Select exact expiry date

I have this record in expiry_date column:
2015-04-30 04:15:29
2015-04-22 06:02:07
I need to select where the record is 26 days from expiring. Right now I'm using this which is not working. No records were selected.
SELECT * FROM `client` WHERE `expiry_date` = DATE_ADD(NOW(), INTERVAL 26 DAY)
I've searched this website and many of the answers are using <= operator. This solution partially work. It selects both of my record when I only need 2015-04-30 04:15:29 in expiry_date column.
How do I exactly select date that is going to expired and not all date?
The easy solution to this is to use the date function:
WHERE DATE(expiry_date) = DATE_ADD(CURRENT_DATE, INTERVAL 26 DAY)
However, this prevents the use of an index on expiry_date. An alternative that does work with indexes is:
WHERE expiry_date >= DATE_ADD(CURRENT_DATE, INTERVAL 26 DAY) AND
expiry_date < DATE_ADD(CURRENT_DATE, INTERVAL 26 + 1 DAY)
The reason you're having this issue is that expiry_date is a type of datetime so the time makes it not equal. Just change your code to be:
SELECT * FROM client WHERE DATE(expiry_date) = DATE(DATE_ADD(NOW(), INTERVAL 26 DAY))

comparing dates by month and year in mysql

I have a table containing data about events and festivals with following columns recording their start and end dates.
Start_Date
End_Date
date format is in YYYY-MM-DD. I need to fetch event details with the following condition.
Need to fetch all events which start with a current month and there end dates can be anything say currentDate+next30days.
I am clear about end date concept. but not sure how I can fetch data whose start dates are in a current month.
For this, I need to compare current year and current month against the Start_Date column in my database.
Can anyone help me to point out as how I can do that?
select * from your_table
where year(Start_Date) = year(curdate())
and month(Start_Date) = month(curdate())
and end_date <= curdate() + interval 30 day
I don't like either of the other two answers, because they do not let the optimizer use an index on start_date. For that, the functions need to be on the current date side.
So, I would go for:
where start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
All the date functions are on curdate(), which does not affect the ability of MySQL to use an index in this case.
You can also include the condition on end_date:
where (start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
) and
end_date <= date_add(curdate(), interval 30 day)
This can still take advantage of an index.
DateTime functions are your friends:
SELECT
*
FROM
`event`
WHERE
(MONTH(NOW()) = MONTH(`Start_Date`))
AND
(`End_Date` <= (NOW() + INTERVAL 30 DAY))
AND
(YEAR(NOW()) = YEAR(`Start_Date`))
Comparing the year and month separately feels messy. I like to contain it in one line. I doubt it will make a noticeable difference in performance, so its purely personal preference.
select * from your_table
where LAST_DAY(Start_Date) = LAST_DAY(curdate())
and end_date <= curdate() + interval 30 day
So all I'm doing is using the last_day function to check the last day of the month of each date and then comparing this common denominator. You could also use
where DATE_FORMAT(Start_Date ,'%Y-%m-01') = DATE_FORMAT(curdate(),'%Y-%m-01')

select all records created within the hour

startTimestamp < date_sub(curdate(), interval 1 hour)
Will the (sub)query above return all records created within the hour? If not will someone please show me a correct one? The complete query may look as follows:
select * from table where startTimestamp < date_sub(curdate(), interval 1 hour);
Rather than CURDATE(), use NOW() and use >= rather than < since you want timestamps to be greater than the timestamp from one hour ago. CURDATE() returns only the date portion, where NOW() returns both date and time.
startTimestamp >= date_sub(NOW(), interval 1 hour)
For example, in my timezone it is 12:28
SELECT NOW(), date_sub(NOW(), interval 1 hour);
2011-09-13 12:28:53 2011-09-13 11:28:53
All together, what you need is:
select * from table where startTimestamp >= date_sub(NOW(), interval 1 hour);

How do I get Timestamp minus 6 weeks in MySQL?

I have a field named timestamp. This is the last time a member was logged in.
I am looking to include a where clause in a query for something like
WHERE timestamp > todays date - 6 weeks
How would I do this?
I am trying to only include users that have logged in in the last 6 weeks.
Thanks
I find this syntax more readable than date_sub, but either way works.
WHERE timestamp >= NOW() - INTERVAL 6 WEEK
If you want to go by "Today" (midnight) instead "now" (current time), you would use this
WHERE timestamp >= DATE(NOW()) - INTERVAL 6 WEEK
where column>=date_sub(now(), interval 6 week)
This link demonstrates how you might acquire a timestamp of yesterday using the format DATE_ADD(CURDATE(), INTERVAL -1 DAY), therefore your query would probably be:
WHERE timestamp > DATE_ADD(CURDATE(), INTERVAL -42 DAY)
You can use between and now():
select somevalue
from yourtable
where yourtimestamp between now() - interval 1 day and now()
for TIMESTAMP there is a TIMESTAMPADD() function
SELECT TIMESTAMPADD(WEEK, -6, CURRENT_TIMESTAMP)
this will return the timestemp of 6 weeks ago
or in the case like the question
SELECT * FROM users
WHERE lastlogin > TIMESTAMPADD(WEEK, -6, CURRENT_TIMESTAMP)
Any luck yet. Have you tried:
>= DATE_SUB(NOW(), INTERVAL 6 WEEK)