Query Database to See if Now is Between Two Dates - mysql

I read how I can query between two dates here, but I'm trying to do the opposite. I have a database of events, with start days and end days. I'm trying to check to see if now() is between any start days AND end days.
Of note, my events are cyclical so I don't care about the years. To use the data format in my database I just use 2000 for everything. I have events such as the Christmas season (2000-12-01 to 2000-12-25), Independence Day (2000-06-25 to 2000-07-04), and so forth.
At first I was thinking about doing something like:
SELECT * FROM `table` WHERE MONTH(NOW()) >= MONTH(`start`) AND DATE(NOW()) >= DATE(`start`) AND MONTH(NOW()) <= MONTH(`end`) AND DATE(NOW()) <= DATE(`end`)
But then I realized a major flaw in periods of time that span multiple months. If today is 27JUN then I'd like the Independence Day row to return, but while 27 >= 25, 27 <= 4 is not the case.
I was thinking of seeing if I can convert NOW(), start, and end to a timestamp to allow me to compare them, but discounted the idea because I might have something with a start date of 2000-12-26 and an end date of 2000-01-01 (remembering that I'm ignoring the year).
Is there a better way to store month/date pairs instead of dates? Or what can I do to fix my database query?

The current date has to be adjusted back to year 2000 before comparing to start and end dates. If the end date is before start date, the year of the end date is actually the year after the start date. Try this:
SELECT * from `table`
WHERE
(`end` >= `start` AND
DATE_ADD(CURDATE(), INTERVAL 2000-YEAR(CURDATE()) YEAR)
BETWEEN `start` AND `end`)
OR
(`end` < `start` AND
DATE_ADD(CURDATE(), INTERVAL 2000-YEAR(CURDATE()) YEAR)
BETWEEN `start` and DATE_ADD(`end`, INTERVAL 1 YEAR))
OR:
SELECT * from `table`
WHERE
CASE
WHEN `end` >= `start` THEN
DATE_ADD(CURDATE(), INTERVAL 2000-YEAR(CURDATE()) YEAR) BETWEEN `start` AND `end`
ELSE
DATE_ADD(CURDATE(), INTERVAL 2000-YEAR(CURDATE()) YEAR) BETWEEN `start` and DATE_ADD(`end`, INTERVAL 1 YEAR)
END
Use CURDATE() instead of NOW() cos NOW() has the time component that is not needed.

SELECT * FROM table WHERE CURDATE() between dateStart and dateEnd
where dateStart is your past date and dateEnd is your future date

Related

MySQL 5.6 - select results where the most recent of multiple datetime columns is 1 month ago at least

I have a table with multiple datetime columns in a mySQL 5.6 database.
email_id
email_sent_date (datetime)
email_replied_date (datetime)
email_bounced_date(datetime)
email_archived (datetime)
I want to retrieve all emails where the latest datetime of the group (email_sent_date,email_replied_date, email_bounced_date, email_archived) is at least 1 month ago from today.
I would like to do something like this, even though i think I can't use this max(), but you'll get a sense of what I am trying to achieve:
SELECT *
FROM table
WHERE MAX(email_sent_date,email_replied_date, email_bounced_date, email_archived) <= CURDATE() - INTERVAL 30 DAY
How to achieve this ?
You want the function greatest(), not max():
SELECT *
FROM table
WHERE GREATEST(email_sent_date, email_replied_date, email_bounced_date, email_archive) <= CURDATE() - INTERVAL 30 DAY;
Note: If any of the values are NULL, then the row will be filtered out.
I prefer explicit comparisons because I think the logic is easier to follow:
SELECT *
FROM table
WHERE email_sent_date <= CURDATE() - INTERVAL 30 DAY AND
email_replied_date <= CURDATE() - INTERVAL 30 DAY AND
email_bounced_date <= CURDATE() - INTERVAL 30 DAY AND
email_archive <= CURDATE() - INTERVAL 30 DAY;
EDIT:
Handling NULL values requires explicit checks. Perhaps:
SELECT *
FROM table
WHERE (email_sent_date <= CURDATE() - INTERVAL 30 DAY OR email_sent_date IS NULL) AND
(email_replied_date <= CURDATE() - INTERVAL 30 DAY OR email_replied_date IS NULL) AND
(email_bounced_date <= CURDATE() - INTERVAL 30 DAY OR email_bounced_date IS NULL) AND
(email_archive <= CURDATE() - INTERVAL 30 DAY OR email_archive IS NULL);

mysql query how to show each day's total cash sale for the current week

I have the following mysql query which shows the each day's total cash sale for the current week.
SELECT
sum(Price) as totalprice,
WEEKDAY(CreatedOn) as dayno,
DATE(CreatedOn) as CreatedOn,
AgentID
FROM records
WHERE CreatedOn BETWEEN (CURDATE()-WEEKDAY(CURDATE())) AND CURDATE()
GROUP BY DATE(CreatedOn)
When I run the query it looks like this:
There are records on 30th November(today's date). So,
day 0 (Monday) no cash sale
day 1 (Tuesday) $5049
day 2 (Wednsday) $99
Nothing is displayed for day 3 (Thursday/today). I cannot figure out the reason there are definitely record in the database but cannot get them to be displayed. I would appreciate any help.
CURDATE() is today's date but at 00:00:00+0000000
"push up" the higher date by 1 day and avoid using between for date/time ranges:
WHERE CreatedOn >= date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
AND CreatedOn < date_add(CURDATE(), INTERVAL 1 DAY)
select date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
, date_add(CURDATE(), INTERVAL 1 DAY)
The condition in the query currently specifies on or before midnight today, so any rows for today after midnight are going to be excluded.
I think you are intending to specify CreatedOn before midnight of the following day.
I also suggest you don't subtract an integer value from a date/datetime, and instead use the INTERVAL syntax
WHERE CreatedOn >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
AND CreatedOn < CURDATE() + INTERVAL 1 DAY
To test those expressions before we include them in a query, we can run a SELECT statement:
SELECT CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
, CURDATE() + INTERVAL 1 DAY
and verify that those expressions are returning what we expect, the values we want to use. For testing, we can replace CURDATE() with a date value to test the return for days other than today.

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')

From the timestamp in SQL, selecting records from today, yesterday, this week, this month and between two dates php mysql

Hopefully, it's an easy solution, but I am trying to filter the data for the following:-
Today
Yesterday
This Week
This Month
In between two dates.
The date I get from the database is basically a timestamp.
This is what I tried:-
Today
SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 DAY)
Yesterday
SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 7 DAYS)
...
It's not really working.
Any idea?
If you're selecting by date only, base your calculations on CURDATE (which returns date only) rather than NOW (which returns date and time). These examples will catch all times within the day ranges:
Today: WHERE timestamp >= CURDATE()
Yesterday: WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND timestamp < CURDATE()
This month: WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY)
Between the two dates 3 June 2013 and 7 June 2013 (note how the end date is specified as 8 June, not 7 June): WHERE timestamp >= '2013-06-03' AND timestamp < '2013-06-08'
The "this week" depends on which day you start your week; I'll leave that to you. You can use the DAYOFWEEK function to tweak CURDATE() to the proper ranges.
Addendum: OP's column type was INTEGER, storing a UNIX timestamp, and my answer assumed the column type was TIMESTAMP. Here's how to do all the same things with a UNIX timestamp value and still maintain optimization if the column is indexed (as the answers above will do if the TIMESTAMP column is indexed)...
Basically, the solution is to just wrap the beginning and/or ending dates in the UNIX_TIMESTAMP function:
Today: WHERE timestamp >= UNIX_TIMESTAMP(CURDATE())
Yesterday: WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 DAY)) AND timestamp < UNIX_TIMESTAMP(CURDATE())
This month: WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY))
Between the two dates 3 June 2013 and 7 June 2013 (note how the end date is specified as 8 June, not 7 June): WHERE timestamp >= UNIX_TIMESTAMP('2013-06-03') AND timestamp < UNIX_TIMESTAMP('2013-06-08')

How do I select between the 1st day of the current month and current day in MySQL?

I need to select data from MySQL database between the 1st day of the current month and current day.
select*from table_name
where date between "1st day of current month" and "current day"
Can someone provide working example of this query?
select * from table_name
where (date between DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), interval 30 day), interval 1 day) AND CURDATE() )
Or better :
select * from table_name
where (date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )
I was looking for a similar query where I needed to use the first day of a month in my query.
The last_day function didn't work for me but DAYOFMONTH came in handy.
So if anyone is looking for the same issue, the following code returns the date for first day of the current month.
SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);
Comparing a date column with the first day of the month :
select * from table_name where date between
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE
select * from table_name
where `date` between curdate() - dayofmonth(curdate()) + 1
and curdate()
SQLFiddle example
I have used the following query. It has worked great for me in the past.
select date(now()) - interval day(now()) day + interval 1 day
try this :
SET #StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET #EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= #StartDate and date < #EndDate);
Complete solution for mysql current month and current year, which makes use of indexing properly as well :)
-- Current month
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
-- Current year
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFYEAR(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
select * from table
where date between
(date_add (CURRENT_DATE, INTERVAL(1 - DAYOFMonth(CURRENT_DATE)) day)) and current_date;
select * from <table>
where <dateValue> between last_day(curdate() - interval 1 month + interval 1 day)
and curdate();
I found myself here after needing this same query for some Business Intelligence Queries I'm running on an e-commerce store. I wanted to add my solution as it may be helpful to others.
set #firstOfLastLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)))-1 DAY);
set #lastOfLastLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH));
set #firstOfLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)))-1 DAY);
set #lastOfLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH));
set #firstOfMonth = DATE_ADD(#lastOfLastMonth, INTERVAL 1 DAY);
set #today = CURRENT_DATE;
Today is 2019-10-08 so the output looks like
#firstOfLastLastMonth = '2019-08-01'
#lastOfLastLastMonth = '2019-08-31'
#firstOfLastMonth = '2019-09-01'
#lastOfLastMonth = '2019-09-30'
#firstOfMonth = '2019-10-01'
#today = '2019-10-08'
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
SELECT date_sub(current_date(),interval dayofmonth(current_date())-1 day) as first_day_of_month;
I had some what similar requirement - to find first day of the month but based on year end month selected by user in their profile page.
Problem statement - find all the txns done by the user in his/her financial year. Financial year is determined using year end month value where month can be any valid month - 1 for Jan, 2 for Feb, 3 for Mar,....12 for Dec.
For some clients financial year ends on March and some observe it on December.
Scenarios - (Today is `08 Aug, 2018`)
1. If `financial year` ends on `July` then query should return `01 Aug 2018`.
2. If `financial year` ends on `December` then query should return `01 January 2018`.
3. If `financial year` ends on `March` then query should return `01 April 2018`.
4. If `financial year` ends on `September` then query should return `01 October 2017`.
And, finally below is the query. -
select #date := (case when ? >= month(now())
then date_format((subdate(subdate(now(), interval (12 - ? + month(now()) - 1) month), interval day(now()) - 2 day)) ,'%Y-%m-01')
else date_format((subdate(now(), interval month(now()) - ? - 1 month)), '%Y-%m-01') end)
where ? is year end month (values from 1 to 12).
The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.
The fastest solution to the real problem of getting the first day of the month returns VARCHAR:
SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;
The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:
SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;
The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself 😊
In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.
So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:
SELECT * FROM table_name
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;
I used this one
select DATE_ADD(DATE_SUB(LAST_DAY(now()), INTERVAL 1 MONTH),INTERVAL 1 day) first_day
,LAST_DAY(now()) last_day, date(now()) today_day
All the responses here have been way too complex. You know that the first of the current month is the current date but with 01 as the date. You can just use YEAR() and MONTH() to build the month date by inputting the NOW() method.
Here's the solution:
select * from table_name
where date between CONCAT_WS('-', YEAR( NOW() ), MONTH( NOW() ), '01') and DATE( NOW() )
CONCAT_WS() joins a series of strings with a separator (a dash in this case).
So if today is 2020-08-28, YEAR( NOW() ) = '2020' and MONTH( NOW() ) = '08' and then you just need to append '01' at the end.
Voila!
Get first date and last date from month and year.
select LAST_DAY(CONCAT(year,'.',month,'.','01')) as registerDate from user;
select date_add(date_add(LAST_DAY(end_date),interval 1 DAY),interval -1 MONTH) AS closingDate from user;
SET #date:='2012-07-11';
SELECT date_add(date_add(LAST_DAY(#date),interval 1 DAY),
interval -1 MONTH) AS first_day