MySQL Date Range Select Queries

July 6th, 2007

Needed to pull rows from a MySQL database, selecting by month, using the MONTH() and YEAR() functions to extract from the datetime stamp. Following returns all records for the month of January, 2007.

SELECT * FROM table WHERE MONTH(datetimefield) = '1' AND YEAR(datetimefield) = '2007'

Or for more detailed date range control, use the DATE() function to extract the date. Returns all records between two dates.

SELECT * FROM table WHERE DATE(datetimefield) BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'

MySQL manual documentation of date and time functions here http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html.