I am trying to check for all records that occurred last month using the following statement.
Select * from statistics
where statistics_date
BETWEEN date_format(NOW() - INTERVAL 1 MONTH, '%Y-%m-01')
AND last_day(NOW() - INTERVAL 1 MONTH )
However, the selection does not include the last day. What I want is from the first second of the month until the last second of the month.
BETWEENis notoriously bad for date and timestamp work because it gets the end date wrong.Here’s what you need:
First, let’s compute the first day of the present month. You had that exactly right.
Next, let’s compute the first day of last month:
Now, we select the records that lie in the interval.
Do you see how the beginning of the date range is chosen with
>=and the end with<? Do you see how I used the first day of the present month for the end of the date range? Those things are important, because timestamps can have days and times in them. Consider the timestamp ‘2013-01-31 23:58’. It happens to be after ‘2012-01-31’ so between won’t catch it.