I have a table with appointments each having start_time and end_time. Is there an efficient way to find overlapping appointments using SQL Server?
Asked
Active
Viewed 239 times
-2
-
Add sample data and expected output. – Pரதீப் Mar 09 '15 at 02:42
-
Kindly provide some sample data and expected results. – Felix Pamittan Mar 09 '15 at 02:42
-
2Have a look at here http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap – Pரதீப் Mar 09 '15 at 02:42
-
Sample Data (id,start_time,end_time): – user1480192 Mar 09 '15 at 04:19
-
Sample Data (id,start_time,end_time): 1,8:00,9:00 2,9:00,10:00 3,12:00,13:00 4,12:30,13:30 5,13:10,13:20 6,14:00,15:00. expected results: 3,4 and 4,5. Note that in the second pair one appointment is entirely within the start and end of the other one. – user1480192 Mar 09 '15 at 04:25
2 Answers
1
Here is one method to find any appointment that overlaps with the next appointment:
select a.*
from (select a.*, lead(start_time) over (order by start_time, id) as next_start_time
from appointments a
) a
where next_start_time < end_time;

Gordon Linoff
- 1,242,037
- 58
- 646
- 786
-
-
It might still be more efficient to use `outer apply`, but you have already accepted another answer. – Gordon Linoff Mar 09 '15 at 12:25
1
It is a simple join:
DECLARE @t TABLE ( ID INT, ST TIME, ET TIME )
INSERT INTO @t
VALUES ( 1, '8:00', '9:00' ),
( 2, '9:00', '10:00' ),
( 3, '12:00', '13:00' ),
( 4, '12:30', '13:30' ),
( 5, '13:10', '13:20' ),
( 6, '14:00', '15:00' )
SELECT t1.ID, t2.ID
FROM @t t1
JOIN @t t2 ON t1.ID < t2.ID
AND (t1.ST > t2.ST
AND t1.ST < t2.ET
OR t1.ET > t2.ST
AND t1.ET < t2.ET)
Output:
ID1 ID2
3 4
4 5
The idea here is to find lines when at least one edge of line is between the edges of other line:
a--------------------b
c-------------d
a--------------------b
c-------------d
a--------------------b
c--------d
If [cd]
overlaps [ab]
at least c
or d
will be between a
and b
.

Giorgi Nakeuri
- 35,155
- 8
- 47
- 75
-
What when [cd] is larger than [ab] meaning c is before a and d is after b? – user1480192 Mar 09 '15 at 10:24
-
@user1480192, since it is a join on itself it will check both situations. That's why there is checking for duplicates. Imagine that you have [x1, x2] and [y1, y2] intervals in your table. Self join will check both sides: it will assign x1 to a, x2 to b, y1 to c, y2 to d. Then it will assign x1 to c, x2 to d, y1 to a y2 to b. – Giorgi Nakeuri Mar 09 '15 at 10:30