How is it possible to use the BETWEEN function in MySQL, to search for dates in any year but between a specific day/month to a specific day/month? Or if it’s not possible using BETWEEN, how else could I accomplish it?
To be more descriptive, I am trying to add a seasonal search to my photo archive website. So if a user chose to search for “summer” photos, it would search photos taken between 21 June and 21 September, but from any year.
If Carlsberg made SQL, I think it would be 🙂
WHERE date BETWEEN 'xxxx-06-21' AND 'xxxx-09-21'
Many thanks
The solution given elsewhere,
WHERE date.MONTH() || date.DAY() BETWEEN '0621' AND '0921', is a good one (and it’s well worth upvoting since it’s fine for most MySQL databases) but I’d like to point out that it (and most queries that involve per-row functions) won’t scale that well to large tables.Granted, my experience is that MySQL is not used that often for the sizes where it would make a huge difference but, in case it is, you should also consider the following.
A trick we’ve used in the past is to combine extra columns with insert/update triggers so that the cost of calculation is only incurred when necessary (when the data changes), rather than on every select.
Since the vast majority of databases are read far more often than written, this amortises that cost over all selects.
For example, add a new column
CHAR(4)calledMMDDand whack an index on it. Then set up insert/update triggers on the table so that thedatecolumn is used to set this new one, based on the formula already provided,date.MONTH() || date.DAY().Then, when doing your query, skip the per-row functions and instead use:
The fact that it’s indexed will keep the speed blindingly fast, at the small cost of a trigger during insert/update and an extra column.
The cost of the trigger is irrelevant since it’s less than the cost of doing it for every select operation. The extra storage required for a column is a downside but, if you examine all the questions people ask about databases, the ratio of speed problems to storage problems is rather high 🙂
And, though this technically “breaks” 3NF in that you duplicate data, it’s a time honoured tradition to do so for performance reasons, if you know what you’re doing (ie, the triggers mitigate the “damage”).