capypad
0 day streak
sql / expert
Snippet

Detecting Interval Overlaps with Self-Joins

Implements a non-equi self-join to detect scheduling conflicts. By comparing two sets of start and end dates, we identify rows that occupy the same resource at the same time.

snippet.sql
sql
1
2
3
4
5
6
SELECT a.booking_id, b.booking_id
FROM room_bookings a
JOIN room_bookings b ON a.room_id = b.room_id
AND a.booking_id < b.booking_id
AND a.start_date < b.end_date
AND a.end_date > b.start_date;
Breakdown
1
a.booking_id < b.booking_id
Prevents comparing a row with itself and ensures each pair is only reported once.
2
a.start_date < b.end_date AND a.end_date > b.start_date
Standard relational logic for identifying overlapping time periods.