Check overlap of date ranges in MySQL
I had such a query with a calendar application I once wrote. I think I used something like this:
... WHERE new_start < existing_end
AND new_end > existing_start;
UPDATE This should definitely work ((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):
- ns - ne - es - ee: doesn't overlap and doesn't match (because ne < es)
- ns - es - ne - ee: overlaps and matches
- es - ns - ee - ne: overlaps and matches
- es - ee - ns - ne: doesn't overlap and doesn't match (because ns > ee)
- es - ns - ne - ee: overlaps and matches
- ns - es - ee - ne: overlaps and matches
Here is a fiddle
SELECT * FROM tbl WHERE
existing_start BETWEEN $newStart AND $newEnd OR
existing_end BETWEEN $newStart AND $newEnd OR
$newStart BETWEEN existing_start AND existing_end
if (!empty($result))
throw new Exception('We have overlapping')
These 3 lines of sql clauses cover the 4 cases of overlapping required.