MySQL Query - Between Today and the Last 30 Days

I want to return all records that have been added to the database in the last 30 days. I need to convert date to mm / dd / yy due to display.

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

My operator cannot limit the records for the last 30 days - he selects all the records.

Can someone point me in the right direction? It seems to me that I'm close.

Thank you, I have a great week.

+108
date mysql select
Jan 11 '10 at
source share
6 answers

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

 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 a portion of the DATE date, so if you save create_date as a DATETIME with a filled part of the time, this query will not select today's records.

In this case, use NOW instead:

 SELECT DATE_FORMAT(create_date, '%m/%d/%Y') FROM mytable WHERE create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW() 
+257
Jan 11 '10 at 11:57
source share
 SELECT * FROM < table_name > WHERE < date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW(); 
+53
Feb 02 '10 at 19:32
source share

DATE_FORMAT returns a string, so you use two strings in your BETWEEN clause, which will not work as you expect.

Instead, convert the date to your format in SELECT and do BETWEEN for the actual dates. For example,

 SELECT DATE_FORMAT(create_date, '%m/%d/%y') as create_date_formatted FROM table WHERE create_date BETWEEN (CURDATE() - INTERVAL 30 DAY) AND CURDATE() 
+10
Jan 11 '10 at 11:57
source share

You can also write this in mysql -

 SELECT DATE_FORMAT(create_date, '%m/%d/%Y') FROM mytable WHERE create_date < DATE_ADD(NOW(), INTERVAL +1 MONTH); 
+8
Jun 25 '14 at 5:50
source share

For current activity and full activity for the previous 30 days, use this, since SYSDATE is a variable for one day, on the previous 30th day there will not be all the data for that day.

 SELECT DATE_FORMAT(create_date, '%m/%d/%Y') FROM mytable WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE() 
+6
Dec 02 2018-11-12T00:
source share

I would do something like this:

 SELECT DATE_FORMAT(create_date, '%m/%d/%Y') FROM mytable WHERE create_date >= (CURDATE() - INTERVAL 30 DAY) 
+2
Oct 24 '16 at 12:07 on
source share



All Articles