I have an Event table that specifies a date range with start_date and end_date fields. I have another date range, specified in code, that defines the current week as ‘week_start’ and ‘week_end’.
I’d like to query all Events for the week. The cases seem to be:
- Event begins and ends within the week
- Event begins before the week, but ends within the week
- Event begins within the week, but ends after the week
- Event begins before the week and also ends after the week
- Events that neither reside within, nor overlap the week at all are ignored
I’m attempting to come up with a query that can handle all these cases. So far I’ve only been able to get cases that handle the week overlaps, or events that are fully internal; Essentially, too many records, or none at all.
In simple words, either a week starts during the event, or an event starts during the week.
Let’s check it:
The event starts during the week.
The week starts during the event.
The event starts during the week.
The week starts during the event.
Note that
BETWEENin expressions above is used just for the sake of brevity.Strict expression looks like this:
, provided that
week.endis aweek.start + INTERVAL 7 DAY.I. e. if you week starts of
Sun, 0:00:00, then it should end onnext Sun, 0:00:00(not onSat, 0:00:00)This expression looks more complex than the one which is commonly used:
, but the former is more efficient and index friendly.
See these articles in my blog for performance comparisons: