The bookings table records reservations of rooms, each with a start and an end time. Find all pairs of bookings for the same room that overlap in time. Return booking_id_1 and booking_id_2 with booking_id_1 < booking_id_2, ordered by booking_id_1 and then booking_id_2 ascending.
Two bookings overlap if each one starts before the other ends. A booking that starts exactly when another ends does not overlap it.
Input Table(s)
bookings
| Column | Type | Meaning |
|---|
| booking_id | INT | Booking identifier |
| room_id | INT | Room that was booked, never NULL |
| start_time | TIMESTAMP | When the booking starts, never NULL |
| end_time | TIMESTAMP | When the booking ends, never NULL |
Primary key: booking_id.
Output Contract
| Column | Type | Meaning |
|---|
| booking_id_1 | INT | The smaller booking id of the overlapping pair |
| booking_id_2 | INT | The larger booking id of the overlapping pair |
Each overlapping pair appears exactly once, with booking_id_1 < booking_id_2. Order by booking_id_1 ascending, then booking_id_2 ascending. Booking ids are unique, so this order is fully determined. No rounding applies.
Example
bookings
| booking_id | room_id | start_time | end_time |
|---|
| 1 | 101 | 2024-03-01 09:00 | 2024-03-01 10:00 |
| 2 | 101 | 2024-03-01 09:30 | 2024-03-01 11:00 |
| 3 | 101 | 2024-03-01 10:00 | 2024-03-01 10:30 |
| 4 | 102 | 2024-03-01 09:00 | 2024-03-01 12:00 |
| 5 | 101 | 2024-03-01 11:00 | 2024-03-01 12:00 |
| 6 | 102 | 2024-03-01 11:30 | 2024-03-01 13:00 |
Expected result:
| booking_id_1 | booking_id_2 |
|---|
| 1 | 2 |
| 2 | 3 |
| 4 | 6 |
Bookings 1 and 2 share 09:30 to 10:00, booking 3 lies entirely inside booking 2, and bookings 4 and 6 share 11:30 to 12:00 in room 102. Bookings 1 and 3 only touch at 10:00, and bookings 2 and 5 only touch at 11:00, so neither pair counts. Booking 4 overlaps bookings 1, 2 and 3 in time but is in a different room.
Constraints and Clarifications
-
bookings
has at most 1,000 rows.
-
start_time < end_time
for every booking, and all times are valid and non-NULL.
-
Treat each booking as the half-open interval from
start_time
up to, but not including,
end_time
. Back-to-back bookings do not overlap.
-
A booking fully contained in another overlaps it, and two bookings with identical times overlap.
-
Bookings in different rooms never form a pair, whatever their times.
-
When three or more bookings overlap one another, return every overlapping pair among them.