How to check if two date ranges overlap in mysql?
If we are guaranteed that date_started
, datefinished
, $DateA
and $DateB
are not NULL, and we're guaranteed that date_started
is not greater than date_finished
...
`s` represents `date_started`
`f` represents `date_finished`
`a` represents the smaller of `$DateA` and `$DateB`
`b` represents the larger of `$DateA` and `$DateB`
Visually:
s-----f overlap
-----+-----+----- -------
a-b | | NO
a---b | YES
a-----b | YES
a---------b YES
a-----------b YES
a---b | YES
a-----b YES
a-------b YES
| a-b | YES
| a---b YES
| a-----b YES
| a-b YES
| | a-b NO
We can easily detect when there's no "overlap" of the ranges:
( a > f OR b < s )
And we can easily negate that to return "true" when there is an "overlap":
NOT ( a > f OR b < s )
Converting that to SQL:
NOT ( GREATEST('{$dateA}','{$dateB}') < p.date_started
OR LEAST('{$dateA}','{$dateB}') > p.date_finished
)