Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlapping date range MySQL

I have the following data;

ID  startDate               endDate
-----------------------------------------------
1   2010-03-01 10:00:00     2010-03-01 12:00:00
2   2010-03-01 12:30:00     2010-03-01 15:30:00
3   2010-03-01 15:30:00     2010-03-01 18:30:00

What I want to do is check that a start and end date don't fall inside the startDate and endDate ranges in my data.

So for example, the following would be OK;

startDate               endDate
-----------------------------------------------
2010-03-01 12:00:00     2010-03-01 12:30:00
2010-03-01 18:30:00     2010-03-01 21:00:00

but the following dates would fail, as they would overlap;

startDate               endDate
-----------------------------------------------
2010-03-01 09:00:00     2010-03-01 13:00:00 (overlaps ID 1)
2010-03-01 10:30:00     2010-03-01 11:00:00 (overlaps ID 1)
2010-03-01 18:00:00     2010-03-01 19:00:00 (overlaps ID 3)

I'm pulling my hair out because I can get one or two of the above 3 test date ranges to fail but not all of them.

I am using MySQL.

like image 228
J.C Avatar asked May 30 '26 11:05

J.C


1 Answers

A query to select overlaps (I'd name the columns startTime & endTime though, as Time seems important...):

WHERE 
<start> < endDate
AND
<end> > startDate
like image 81
Wrikken Avatar answered Jun 01 '26 00:06

Wrikken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!