I want to get first day of every corresponding month of current year. For example, if user selects \'2010-06-15\', query demands to run from \'2010-06-01\' instead of \'2010
You can use DATE_FORMAT() function in order to get the first day of any date field.
SELECT DATE_FORMAT(CURDATE(),'%Y-%m-01') as FIRST_DAY_CURRENT_MONTH
FROM dual;
Change Curdate() with any other Date field like:
SELECT DATE_FORMAT(purchase_date,'%Y-%m-01') AS FIRST_DAY_SALES_MONTH
FROM Company.Sales;
Then, using your own question:
SELECT *
FROM
hrm_attendanceregister
WHERE
hrm_attendanceregister.Date) >=
DATE_FORMAT(CURDATE(),'%Y-%m-01')
You can change CURDATE() with any other given date.
I'm surprised no one has proposed something akin to this (I do not know how performant it is):
CONCAT_WS('-', YEAR(CURDATE()), MONTH(CURDATE()), '1')
Additional date operations could be performed to remove formatting, if necessary
date_add(subdate(curdate(), interval day(?) day), interval 1 day)
change the ? for the corresponding date
Is this what you are looking for:
select CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE);
select big.* from
(select @date := '2010-06-15')var
straight_join
(select * from your_table where date_column >= concat(year(@date),'-',month(@date),'-01'))big;
This will not create a full table scan.
There is actually a straightforward solution since the first day of the month is simply today - (day_of_month_in_today - 1)
:
select now() - interval (day(now())-1) day
Contrast that with the other methods which are extremely roundabout and indirect.
Also, since we are not interested in the time component, curdate() is a better (and faster) function than now()
. We can also take advantage of subdate()'s 2-arity overload since that is more performant than using interval
. So a better solution is:
select subdate(curdate(), (day(curdate())-1))