← Back to SQL, page 15

sql-0282 · Medium mid

Write a query that finds pairs of room bookings that overlap in time.

Two half-open intervals [s1, e1) and [s2, e2) overlap when s1 < e2 AND s2 < e1. Self join the bookings on the same room with that condition and a.id < b.id so each pair appears once. Back-to-back bookings, where one ends exactly when the next starts, do not overlap under half-open rules.

Full answer
sql
WITH b(id, room, s, e) AS (VALUES
  (1, 'A', '09:00', '10:30'), (2, 'A', '10:00', '11:00'),
  (3, 'A', '11:00', '12:00'), (4, 'B', '09:30', '10:30'))
SELECT x.id AS booking, y.id AS clashes_with
FROM b x JOIN b y ON x.room = y.room AND x.id < y.id AND x.s < y.e AND y.s < x.e
ORDER BY booking;
bookingclashes_with
12

Bookings 1 and 2 overlap between 10:00 and 10:30. Booking 3 starts exactly when booking 2 ends, so with half-open intervals it is not a clash. Booking 4 is in another room.

The condition a.start < b.end AND b.start < a.end covers every overlap shape: partial, one inside the other, and identical. Trying to list the cases separately usually misses one.

PostgreSQL can prevent overlaps at write time with range types and an exclusion constraint, EXCLUDE USING gist (room WITH =, tsrange(start, end) WITH &&), which needs the btree_gist extension (not run here).

sql
WITH b(id, room, s, e) AS (VALUES
  (1, 'A', '09:00', '10:30'), (2, 'A', '10:00', '11:00'),
  (3, 'A', '11:00', '12:00'), (4, 'B', '09:30', '10:30'))
SELECT x.id AS booking, y.id AS clashes_with
FROM b x JOIN b y ON x.room = y.room AND x.id < y.id AND x.s < y.e AND y.s < x.e
ORDER BY booking;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Overlap test: s1 < e2 AND s2 < e1
  • Half-open intervals let back-to-back bookings coexist
  • Self join on the same room with a.id < b.id
  • PostgreSQL exclusion constraints can prevent overlaps

Common mistakes

  • Listing overlap cases separately and missing one
  • Using <= and flagging back-to-back bookings as clashes

Follow-ups

  • How would you find free slots in a day?
  • How would you prevent overlaps in SQLite?

Tips

  • Draw the two intervals on a line