I have a bunch of timestamped rows (using the ‘datetime’ data type)
I want to select all the rows that have a timestamp that is within a particular month.
The column is indexed so I can’t do MONTH(timestamp) = 3 because that’ll make this index unuseable.
If I have year and month variables (in perl), is there a horrific bit of SQL I can use like:
timestamp BETWEEN DATE($year, $month, 0) AND DATE($year, $month, 31);
But nicer, and actually works?
I would actually go with the idea you proposed ; maybe with a small difference :
(Of course, up to you the use
$yearand$monthproperly)Note the
< '2010-02-01'part : you might have to consider this, if you have dates that include the time.For instance, if you have a line with a date like
'2010-01-31 12:53:12', you probably want to have that line selected — and, by default,'2010-01-31'means'2010-01-31 00:00:00'.Maybe that doesn’t look ‘nice’ to the eye ; but it’ll work ; and use the index… It’s the kind of solution I generaly use when I have that kind of problem.