2

I'm creating a set of "archive" pages that are specified by year and month. In my table I have a datetime field called posted. I want to select all rows that are in a particular month.

I've thought of two solutions:

(1) Use string matching:

SELECT ... WHERE posted LIKE '2009-06%'

(2) Use some MySQL extraction functions:

SELECT ... WHERE YEAR(posted)=2009 AND MONTH(posted)=6

Which of these will be quicker, and are there any better solutions?

2 Answers 2

7
SELECT   *
WHERE    posted >= '2009-06-01'
         AND posted < '2009-07-01'

This one will efficiently use an index on posted, unlike both your queries.

Note that if your were keeping posted as a VARCHAR, then the following query:

SELECT ... WHERE posted LIKE '2009-06%'

would use the index too.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't the BETWEEN operator be more appropriate here?
Hmm, I guess not, as you have to do CASTs in MySQL with BETWEEN on dates: dev.mysql.com/doc/refman/5.0/en/…
@R.Bemrose: it would return the records that fall on '2009-07-01 00:00:00' exactly for both June and July queries. It can be a problem.
Thanks, this worked a treat. For some reason it didn't occur to me that I could use < > selectors...
1

Disregarding reservations about this design, the standard syntax would be "BETWEEN first-date AND last-date", or (if you're using less than date granularity), "posted >= first-date AND posted < last-date + 1".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.