Recently, I have been getting familiar with PostgreSQL(using 8.2) and found the date_trunc function extremely useful for easily matching time stamps between certain days/months/etc.
The real usefulness of the function, I believe, comes from the fact that it keeps the output in the format of a timestamp.
I have had to switch to mySQL(5.0) and find some of the date functions rather lacking in comparison. The extract function seems useful and the date function I have found solves some of my problems, but is there any way to replicate PostgreSQL’s date_trunc?
Following is an example of how I used to use date_trunc to match queried timestamps to only the last 4 months including the current month, but only if a week has passed into this month already:
WHERE date_trunc('month', QUERY_DATE) BETWEEN
date_trunc('month', now()) - INTERVAL '4 MONTH' AND
date_trunc('month', now() - INTERVAL '1 WEEK')
I have no idea how to recreate such a stipulation in mySQL. So, my question at the end of the day, is whether this type of query can be accomplished in mySQL by trying replicate date_trunc(and how) or whether I need to start looking at these types of queries in a different way to make them work in mySQL(and suggestions on how to do that)?
Indeed,
EXTRACTlooks like it’s going to be the closest match for this specific case.Your original code in PG:
Using
EXTRACT:While it should be functionally identical, this is actually mangling the dates into a YYYYMM string before doing the comparison.
Another option would be using
DATE_FORMATto rebuild the date string and force it to the beginning of the month:Also, be aware that MySQL is really poor at dealing with date ranges, even when the field is indexed. You’re probably going to end up with a full table scan if you aren’t careful.