Returning records from the last 3 months only in MySQL

I have a table with a timestamp field. How do I get data from the last 3 months?

In particular, March is my current month let say, 03/2012. I need to return records from the months March, February, and January only.


3 months before today:

select * from table where timestamp >= now()-interval 3 month;

Start with first of month:

select * from table where timestamp >= last_day(now()) + interval 1 day - interval 3 month;

To get the first day of the current month, you could use this:

DATE_FORMAT(CURDATE(), '%Y-%m-01')

if current date is 2013-03-13, it will return 2013-03-01, and we can just substract 2 months from this date to obtain 2013-01-01. Your query could be like this:

SELECT *
FROM yourtable
WHERE data >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH

Assuming you're using SQL Server (Oracle, MySQL and others have similar date functions), you can use the dateadd function to add or subtract an interval to the current date.

If you want a full three months, you can subtract 3 months from today : DATEADD(m,-3,getdate())

But, as you state, you only want data from January, February and March. You have to make some calculation based on today's date: dateadd(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate())) + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))

And in the end, get a query like

SELECT fields 
FROM table 
WHERE timestampfield > DATEADD(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate()))  + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))

--- edit --- erf, I just noticed the "mysql" tag... you can get more information on MySQL date functions here : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html