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)):

  1. ns - ne - es - ee: doesn't overlap and doesn't match (because ne < es)
  2. ns - es - ne - ee: overlaps and matches
  3. es - ns - ee - ne: overlaps and matches
  4. es - ee - ns - ne: doesn't overlap and doesn't match (because ns > ee)
  5. es - ns - ne - ee: overlaps and matches
  6. 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.


Lamy's answer is good, but you can optimize it a little more.

SELECT * FROM tbl WHERE
existing_start BETWEEN $newSTart AND $newEnd OR
$newStart BETWEEN existing_start AND existing_end

This will catch all four scenarios where the ranges overlap and exclude the two where they don't.