tags:

views:

364

answers:

3

Hi All,

I need to select all rows in my database that were created last month. For example, if the current month is January, then I want to return all rows that were created in December, if the month is February, then I want to return all rows that were created in January. I have a date_created column in my database that lists the date created in this format: 2007-06-05 14:50:17.

Thanks!

Devin

+6  A: 
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
hobodave
A: 

select fields FROM table WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');

this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.

ggiroux
@ggiroux - It does have to convert the date to a character type before applying the LIKE though.
martin clayton
yes indeed, but still an improvement over the selected answer IMHO (IFF date_created is indexed)
ggiroux
+1  A: 

Here's another alternative. Assuming you have an indexed DATE or DATETIME type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range query rather than an index query when viewed with EXPLAIN.

SELECT
    * 
FROM
    table
WHERE 
    date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) 
AND
    date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )
martin clayton
this will get you the records which were created on the first day of the current month though.
ggiroux
@ggiroux - Indeed. Thanks - fixed.
martin clayton
+1 then - much cleaner than mine :)
ggiroux