Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select First Day of Year and Month

How to find first day of year in SELECT?

SELECT `DATE`,`SomeValue1`,`SomeValue2`
FROM `SomeTableName`
WHERE (`DATE` >= [...first day of the year in date format...])

I found this for month - but I don't QUITE have the grasp enough for year: (I was looking for this for a separate query to find data between beginning of month and now)

WHERE (`DATE` between  DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() ) 
like image 838
Mark Bogner Avatar asked Aug 23 '13 21:08

Mark Bogner


People also ask

How do I get the first day of the current year in SQL?

Here's a fairly simple way; SELECT DATEFROMPARTS(YEAR(GETDATE()), 1, 1) AS 'First Day of Current Year'; SELECT DATEFROMPARTS(YEAR(GETDATE()), 12, 31) AS 'End of Current Year'; It's not sexy, but it works. Only available starting from Sql Server 2012.

How do I select month and year from date in SQL?

To get the year and the month columns, use the EXTRACT(part FROM date) function. In this solution, the part argument is replaced by YEAR and MONTH to get the year and the month separately, each in its own column. You can learn more about EXTRACT() in the official MySQL documentation.

How can I get first Monday of the month in MySQL?

SET @firstday = '2013-04-01'; SELECT ADDDATE( @firstday , MOD((9-DAYOFWEEK(@firstday)),7)) as first_monday; The param @firstday is the first day of the month you want to search. Note that sunday is the first day of a week, monday is the second day. The answer was helpful.


1 Answers

To get the first day of the current year, I use:

SELECT MAKEDATE(year(now()),1);

So in your query you would write:

where `date` >= MAKEDATE(year(now()),1)

I quite commonly do something like a sales report for the past full 2 years, but I always want to start at the beginning of a year. So shows 2 full years and the year to date.

where date>= MAKEDATE(year(now()-interval 2 year),1)

But to further complicate it, our financial years starts on the first of May. I always want to start on the first of May.

where date >= MAKEDATE(year(now()-interval 2 year),1) + interval 120 day

or as an alternative

where date >= MAKEDATE(year(now()-interval 2 year),121)

The first of May being the 121st day of a the year. But this method does not work in leap years.

The leap year proof version is:

where date => select MAKEDATE(year(now()-interval 5 year),1) + interval 4 month

Which will always return a xxxx-05-01 date, whether a leap year or not.

like image 189
Tim Bray Avatar answered Oct 05 '22 23:10

Tim Bray