Get values between now and now + 5days in php mysql - mysql

I want to fetch all the values between followupdate = now and followupdate = now + 5days. Currently I'm using this query which is not returning today's values though it is returning the next 5 days values
SELECT * FROM leads WHERE followupdate >= NOW() AND followupdate <= NOW() + INTERVAL 5 DAY;

Try the following query:
SELECT * FROM leads WHERE followupdate >= DATE(NOW()) AND followupdate <= DATE(NOW() + INTERVAL 5 DAY);
As NOW returns the entire timestamp use DATE() to get today's date.

You can use CURDATE() to get today's date, then add 5 to it.
SELECT
*
FROM
leads
WHERE
followupdate >= CURDATE() AND followupdate <= DATE_ADD(CURDATE(), INTERVAL 5 DAY);

Related

How DO I fetch last Week and current week

How do I fetch last week data from monday time (00:00:01) and end on sunday time (23:59:59)...
same as this current week from monday time (00:00:01) and end on sunday time (23:59:59)
WHat I tried!
$query = "SELECT users.name,count(*) as count,
campaign.campaign_name,
campaign.payout_cost*count(*) as totalPrice
FROM users
JOIN transactions on users.uid=transactions.uid
JOIN campaign on campaign.campaign_id_id=transactions.campaign_id
WHERE uid=$uid
AND `date` >= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY)
AND `date` < DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY)
GROUP BY campaign.campaign_name_name ";
You are on the right track by avoiding functions like week() on the column -- that just messes up the optimizer. On the other hand, the uid parameter should be passed as a parameter rather than munging the query string.
You want to use the weekday() function because you want weeks to start on a Monday. Just some arcaneness of MySQL: weekday() returns 0 for Monday whereas dayofweek() returns 2 for Monday.
So, the logic for the current week would be:
date >= curdate() - interval weekday(curdate()) day and
date < curdate() + interval 7 - weekday(curdate()) day
For last week, this would be:
date >= curdate() - interval 7 + weekday(curdate()) day and
date < curdate() + interval - weekday(curdate()) day
Notes that curdate() (or current_date) returns the current date with no time component, so no date() is required.
Couple of ways to do it...
select data from tableName
where date between date_sub(now(),INTERVAL 1 WEEK) and now();
select data FROM tableName
wherdate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
You can use WEEK() function, which returns the week number for a given date, by adding
AND WEEK(date-INTERVAL 1 DAY) = WEEK(NOW()) - 1 to get current week's data starting from monday upto sunday,
and
AND WEEK(date-INTERVAL 1 DAY) = WEEK(NOW()) - 2 for the previous week's data
into the WHERE condition after WHERE uid=$uid
such as
$query = "SELECT c.campaign_name,
COUNT(*) as total_count,
SUM(c.payout_cost) as total_payout
FROM transactions t
JOIN campaign c
ON c.campaign_id = t.campaign_id
WHERE uid = $uid
AND WEEK(date - INTERVAL 1 DAY) = WEEK(NOW()) - 1
GROUP BY c.campaign_name ";
and replace WEEK(NOW()) - 1 with WEEK(NOW()) - 2, also
Demo

mysql select between two dates has odd behavior

I am selecting all records between NOW() and specific X day interval and came across this odd behavior that I don't understand.
I am checking 24 hours into the future and 24 hours into the past:
select * from table where date between NOW() and NOW() + 1 interval day; //works
select * from table where date between NOW() and NOW() - 1 interval day; //no records
But if I reverse the between call:
select * from table where date between NOW() + 1 interval day AND NOW(); //no records
select * from table where date between NOW() - 1 interval day AND NOW(); //works
Why does one call into the future work, but the same call into the past not work?...and if I reverse between parameters, the opposite behavior happens - does not work 24 hours into the future but does work 24 hours into the past.
======================
Adding #TimBiegeleisen explanation below here written out:
date = '2018-05-30' ;
select * from table where date between NOW() and NOW() + 1 interval day;
= date >= '2018-05-30' AND 'date <= 2018-05-31'; //true
select * from table where date between NOW() and NOW() - 1 interval day; records
= date >= '2018-05-30' AND 'date <= 2018-05-29'; //false
AND
select * from table where date between NOW() + 1 interval day AND NOW();
= date >= '2018-05-31' AND date <= '2018-05-30' //false
select * from table where date between NOW() - 1 interval day AND NOW();
= date >= '2018-05-29' and date <= '2018-05-30'; //true
The BETWEEN operator is interpreted a certain way:
WHERE date BETWEEN a AND b
means this:
WHERE date >= a AND date <= b
So the following two queries are equivalent:
select * from table where date between NOW() and NOW() - interval 1 day;
select * from table where date >= NOW() and date <= NOW() - interval 1 day;
Hopefully you can see that in your second query the WHERE condition can never be true, because a date cannot simutaneously be greater than or equal to now and less than now minus one at the same time.
simply put,
For SQL:
WHERE x between a and b
meaning
x >= a
and
x <= b
therefore, we have a <= x <= b or a <= b
PS: it's just about math :)

select dates that are between current date and 3 month from the current date in mysql

I want to select all dates that are between the current date and 3 months before.
I tried using this query but it isn't working right.
$sql = mysql_query("
SELECT *
FROM date
WHERE d_date BETWEEN NOW() AND NOW() - INTERVAL 3 MONTH
");
Please if you could help me write the right syntax.
You need to swap your bounaries, and it will work:
SELECT * FROM date
WHERE d_date BETWEEN now() - INTERVAL 3 MONTH AND now()
For example, this query returns true (SQLFiddle):
SELECT (now() - interval 1 month)
BETWEEN now() - interval 3 month AND now()
SELECT * FROM Table
WHERE anydate_col BETWEEN NOW() AND DATE_ADD( NOW() , INTERVAL +3 MONTH)

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

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