11

I have a DATE, how do I write a where that checks for last month until now (either the first of or just today's day -1 month)?

0

2 Answers 2

33
SELECT * FROM table WHERE dateField > DATE_SUB(NOW(), INTERVAL 1 MONTH)

This selects all rows that have a dateField more recent than current timestamp minus one month (so, for example, given today is 26 Sep 2009 00:56 it would give rows that are more recent than 26 Aug 2009 00:56)

11

Actually, last month until now would be:

From the beginning of the month:

SELECT * FROM table
WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-01')
AND date <= NOW()

Since a month ago: (hopefully you have no future dates on the table)

SELECT * FROM table
WHERE date >= (CURRENT_DATE - INTERVAL 1 MONTH)

Alternatively, you might want only the last month... Say today is September and you want all August, not including any of September... That is what I understand as 'last month'.

SELECT * FROM table
WHERE date >= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01')
AND date < DATE_FORMAT(CURRENT_DATE, '%Y/%m/01')

You could also do for the same result:

SELECT * FROM table
WHERE YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.