Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

mysql

get

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?

like image 613
Nurlan Avatar asked Aug 04 '12 11:08

Nurlan


People also ask

How to SELECT first day of month in MySQL?

In MySQL, there is no direct function to find out the first day but there is a function for finding the day of the month of that particular date so with the help of this we can subtract the previous day date from the given day date to get the first day of the month.

How do you determine the first day of the current month?

1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.

How do I get the current day in MySQL?

MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).

How do I get current month and day in SQL?

We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.


2 Answers

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() ) 
like image 70
aleroot Avatar answered Nov 14 '22 06:11

aleroot


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 
like image 26
Shri Avatar answered Nov 14 '22 06:11

Shri