<p>In MySQL, If I have a list of date ranges (range-start and range-end). e.g.</p>

<pre><code>10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983
</code></pre>

<p>And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?</p>

<p>e.g.</p>

<pre><code>06/06/1983 to 18/06/1983 = IN LIST
10/06/1983 to 11/06/1983 = IN LIST
14/07/1983 to 14/07/1983 = NOT IN LIST
</code></pre>

This is a classical problem, and it's actually easier if you reverse the logic.
Let me give you an example.
I'll post one period of time here, and all the different variations of other periods that overlap in some way.
```
```
|-------------------|          compare to this one
               |---------|                contained within
           |----------|                   contained within, equal start
                   |-----------|          contained within, equal end
           |-------------------|          contained within, equal start+end
     |------------|                       not fully contained, overlaps start
                   |---------------|      not fully contained, overlaps end
     |-------------------------|          overlaps start, bigger
           |-----------------------|      overlaps end, bigger
     |------------------------------|     overlaps entire period
```
```
on the other hand, let me post all those that doesn't overlap:
```
```
|-------------------|          compare to this one
     |---|                                ends before
                                 |---|    starts after
```
```
So if you simple reduce the comparison to:
```
```
starts after end
ends before start
```
```
then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.
For your final NOT IN LIST example, you can see that it matches those two rules.
You will need to decide wether the following periods are IN or OUTSIDE your ranges:
```
```
|-------------|
   |-------|                       equal end with start of comparison period
                         |-----|   equal start with end of comparison period
```
```
If your table has columns called range_end and range_start, here's some simple SQL to retrieve all the matching rows:
```
```
SELECT *
FROM periods
WHERE NOT (range_start > @check_period_end
           OR range_end < @check_period_start)
```
```
Note the
NOT
in there. Since the two simple rules finds all the
non-matching
rows, a simple NOT will reverse it to say:
if it's not one of the non-matching rows, it has to be one of the matching ones
.
Applying simple reversal logic here to get rid of the NOT and you'll end up with:
```
```
SELECT *
FROM periods
WHERE range_start <= @check_period_end
      AND range_end >= @check_period_start
```
```