Update Day of Month - mysql

I have a select statement that is finding all the dates in the column that are on the 9th of the month, regardless of month and year:
SELECT *
FROM tblhosting
WHERE DAY( nextduedate ) =09
I would like to UPDATE the DAY to 10, but leave the month and year alone.
Any help?

UPDATE tableName
SET nextduedate = DATE_ADD(nextduedate,INTERVAL 1 DAY)
WHERE DAY(nextduedate) = 9
SQLFiddle Demo
Source:
DATE_ADD
DATE_ADD

Related

Getting Data from current Year till date

I have the query where i am getting the data but one year back till now,
select * from tblorders
where CreatedDateTime >= DATE_SUB(NOW(),INTERVAL 1 YEAR);
how can i get the data from the start of the current year till date data
start of the current year like 01/01/2021
select * from tblorders
where ( CreatedDateTime between DATE_FORMAT(NOW() ,'%Y-01-01') AND NOW() )
This would return from the beginning of the current year till current date
How about
select * from tblorders
where YEAR(CreatedDateTime) = YEAR(NOW());
DBFiddle: https://www.db-fiddle.com/f/d7h2raMmvxngn1uigPjoB5/0

SQL return values from year to date (YTD)

How to get values from year to date ?I need to display 2 values from ytd current year and previous year without changing query in future. As i undertand, ytd starts from first day of January. For example; from '2018-01-01' until current month of the year, and another query will be for ytd previous year.
Use:
SELECT * FROM TABLE WHERE DATE > DATE_FORMAT(NOW(), '%Y/1/1') AND DATE < NOW();
For this Y2D and:
SELECT * FROM TABLE WHERE DATE > (SELECT DATE_FORMAT((SELECT date_sub(DATE_FORMAT(NOW(), '%Y/1/1'), interval 1 year) AND DATE < (SELECT DATE_FORMAT((SELECT date_sub(NOW(), interval 1 year);
For last years Y2d

How to get last year's date range?

I would like to get a date range between LastYear/1/1 until LastYear/12/31
I know I could do this
date_sub(now(), interval 1 year). But this would get me 2013/03/08. Not sure how to change the day and the month.
SELECT *
FROM orders
WHERE dispatch_date between `LastYear/1/1` AND `LastYear/12/31`
You can easy to create the required dates:
SELECT *
FROM orders
WHERE dispatch_date >= MAKEDATE(YEAR(NOW()) - 1, 1) -- first day of previous year
AND dispatch_date < MAKEDATE(YEAR(NOW()), 1) -- first day of current year
I would suggest you to use YEAR().
SET #LastYear = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));
SELECT *
FROM orders
WHERE dispatch_date
BETWEEN CONCAT(#LastYear,'-01-01') AND CONCAT(#LastYear,'-12-31')

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

MySQL Query to select data from last week?

Hi I have a table with a date field and some other information.
I want to select all entries from the past week, (week start from Sunday).
table values:
id date
2 2011-05-14 09:17:25
5 2011-05-16 09:17:25
6 2011-05-17 09:17:25
8 2011-05-20 09:17:25
15 2011-05-22 09:17:25
I want to select all ids from last week, expected output is 5, 6, 8.
(id 2 not in last week, and id 15 is in current week.)
How to write and SQL Query for the same.
select id from tbname
where date between date_sub(now(),INTERVAL 1 WEEK) and now();
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)
I use the YEARWEEK function specifically to go back to the prior whole calendar week (as opposed to 7 days before today). YEARWEEK also allows a second argument that will set the start of the week or determine how the first/last week of the year are handled. YEARWEEK lets you to keep the number of weeks to go back/forward in a single variable, and will not include the same week number from prior/future years, and it's far shorter than most of the other answers on here.
Simplified form:
Last week data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 1 AND YEAR( date) = YEAR( current_date );
2 weeks ago data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 2 AND YEAR( date) = YEAR( current_date );
SQL Fiddle
http://sqlfiddle.com/#!8/6fa6e/2
You can make your calculation in php and then add it to your query:
$date = date('Y-m-d H:i:s',time()-(7*86400)); // 7 days ago
$sql = "SELECT * FROM table WHERE date <='$date' ";
now this will give the date for a week ago
Probably the most simple way would be:
SELECT id
FROM table
WHERE date >= current_date - 7
For 8 days (i.e. Monday - Monday)
PLEASE people... 'Last week' like the OP asked and where I was looking for (but found none of answers satisfying) is THE LAST WEEK.
If today is Tuesday, then LAST WEEK is Monday A WEEK AGO to Sunday A WEEK AGO.
So:
WHERE
WEEK(yourdate) = WEEK(NOW()) - 1
Or for ISO weeks:
WHERE
WEEK(yourdate, 3) = WEEK(NOW(), 3) - 1
If you're looking to retrieve records within the last 7 days, you can use the snippet below:
SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;
Here is a way to get last week, month, and year records in MySQL.
Last Week
SELECT UserName, InsertTime
FROM tblaccounts
WHERE WEEK(InsertTime) = WEEK(NOW()) - 1
AND MONTH(InsertTime) = MONTH(NOW())
AND YEAR(InsertTime) = YEAR(NOW())
Last Month
SELECT UserName, InsertTime
FROM tblaccounts
WHERE MONTH(InsertTime) = MONTH(NOW()) - 1
AND YEAR(InsertTime) = YEAR(NOW())
Last YEAR
SELECT UserName, InsertTime
FROM tblaccounts
WHERE YEAR(InsertTime) = YEAR(NOW()) - 1;
You'll need to calc which day relative to today is Sunday in your middleware (php, python, etc.)*
Then,
select id
from table
where date >= "$sunday-date" + interval 7 DAY
may be a way to get sunday's date relative to today in MySQL as well; that would be arguably the cleaner solution if not too expensive to perform
It can be in a single line:
SELECT * FROM table WHERE Date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()
A simple way can be this one, this is a real example from my code and works perfectly:
where("actions.created_at >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)")
For more example Like last month, last year, last 15 days, last 3 months
Fetch Last WEEK Record
Using the below MySQL query for fetching the last week records from the mysql database table.
SELECT name, created_at
FROM employees
WHERE
YEARWEEK(`created_at`, 1) = YEARWEEK( CURDATE() - INTERVAL 1 WEEK, 1)
The above query will not work.
After the where clause, if we can not CAST the column value, then it will not work. You should cast the column value.
e.g.:
SELECT.....
WHERE CAST( yourDateColumn AS DATE ) > DATEADD( DAY, -7, CAST( GETDATE() AS DATE )
SELECT id FROM tb1
WHERE
YEARWEEK (date) = YEARWEEK( current_date -interval 1 week )
I often do a quick "last week" check as well and the following tends to work well for me and includes today.
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = Getdate() - 7 /* Seven Days Earlier */
SET #EndDate = Getdate() /* Now */
SELECT id
FROM mytable
WHERE date BETWEEN #StartDate AND #Enddate
If you want this to NOT include today just subtract an extra day from the #EndDate. If I select these two variables today get
#StartDate 2015-11-16 16:34:05.347 /* Last Monday */
#EndDate 2015-11-23 16:34:05.347 /* This Monday */
If I wanted Sunday to Sunday I would have the following.
SET #StartDate = Getdate() - 8 /* Eight Days Earlier */
SET #EndDate = Getdate() - 1 /* Yesterday */
#StartDate 2015-11-15 16:34:05.347 /* Previous Sunday */
#EndDate 2015-11-22 16:34:05.347 /* Last Sunday */
WHERE yourDateColumn > DATEADD(DAY, -7, GETDATE()) ;
You can also use it esay way
SELECT *
FROM inventory
WHERE YEARWEEK(`modify`, 1) = YEARWEEK(CURDATE(), 1)
i Use this for the week start from SUNDAY:
SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY
try this
WHERE trunc(DATE) <= (trunc (sysdate) -5) AND trunc(DATE) >= (trunc (sysdate) -12)
-5 is 5 days back from system date ,, -12 is 12 days back from system date for this example wednesday / or sednesday to wednesday cant recall.
Try this:
Declare #Daytype varchar(15),
#StartDate datetime,
#EndDate datetime
set #Daytype = datename(dw, getdate())
if #Daytype= 'Monday'
begin
set #StartDate = getdate()-7
set #EndDate = getdate()-1
end
else if #Daytype = 'Tuesday'
begin
set #StartDate = getdate()-8
set #EndDate = getdate()-2
end
Else if #Daytype = 'Wednesday'
begin
set #StartDate = getdate()-9
set #EndDate = getdate()-3
end
Else if #Daytype = 'Thursday'
begin
set #StartDate = getdate()-10
set #EndDate = getdate()-4
end
Else if #Daytype = 'Friday'
begin
set #StartDate = getdate()-11
set #EndDate = getdate()-5
end
Else if #Daytype = 'Saturday'
begin
set #StartDate = getdate()-12
set #EndDate = getdate()-6
end
Else if #Daytype = 'Sunday'
begin
set #StartDate = getdate()-13
set #EndDate = getdate()-7
end
select #StartDate,#EndDate
You can try this one. it worked for me :
where date(createdtime) <= date(curdate())-7
In the the above code createdtime is database field name, as individuals this name could vary.
If you already know the dates then you can simply use between, like this:
SELECT id
FROM `Mytable`
where MyDate BETWEEN "2011-05-15" AND "2011-05-21"