my dates in my table are strings in the format:
"10/12/2009"
Now how would one get all the records from a month, lets say June (number “6” being provided)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The short answer to your question is that you can use the
STR_TO_DATEandMONTHfunctions to 1) convert the string representation into a DATE, and 2) extract the month component from the date:(This is assuming here that by ’10/12/2009′, you are specifying Oct 12, and not Dec 10. You’d need to adjust the format string if that’s not the case.)
Alternatively, if month is indeed the leading part of the date, you could do a simple string comparison, if the month is the leading component:
(You could eliminate one of those predicates, if you have an exact format specified for the striing value representing the date: either if month is always stored as two digits -OR- the month is never stored with a leading zero.)
If you are passing in an argument for the month, e.g. ‘6’, then you could construct your statement something like this:
If month is the second component of the date, then you could use:
NOTE:
All of the previous example queries will return rows for June of any year (2009, 2010, 2011)
You can extend those examples, and do something similar with the year, using the YEAR function in place of the MONTH function, or for string comparison
Normally, we’d extract rows for a particular month for a particular year, using a date range, for example:
Of course, when the date value is stored as a
DATEdatatype rather than as a VARCHAR, this means we don’t need the STR_TO_DATE and MONTH functions, we can specify a comparison to the native DATE column. This approach allows us to make use of an index on the date column, which can improve query performance on large tables.