Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query - Records between Today and Last 30 Days

Tags:

date

select

mysql

I want to return all records that were added to the database within the last 30 days. I need to convert the date to mm/dd/yy because of display purposes.

create_date between DATE_FORMAT(curdate(),'%m/%d/%Y') AND (DATE_FORMAT(curdate() - interval 30 day,'%m/%d/%Y'))  

My statement fails to limit the records to the last 30 days - it selects all the records.

Can anyone point me in the right direction? It feels like I am close.

Thanks and have a great week.

like image 971
Jason Sweet Avatar asked Jan 11 '10 11:01

Jason Sweet


People also ask

How do I get last 30 days records in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

How do I query between two dates using MySQL?

select *from yourTableName where yourColumnName between 'yourStartingDate' and curdate().

What is interval in MySQL?

MySQL interval is an operator, which is based on the binary search algorithm to search the items and returns the value from 0 to N. It is mainly used to calculate the date and time values. We can use the following syntax to create an interval value: INTERVAL expr unit.


2 Answers

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y') FROM    mytable WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() 

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y') FROM    mytable WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW() 
like image 83
Quassnoi Avatar answered Sep 28 '22 02:09

Quassnoi


SELECT     * FROM     < table_name > WHERE     < date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW(); 
like image 33
Thinkcast Avatar answered Sep 28 '22 03:09

Thinkcast