Check whether two date ranges overlap in SQL
Scheduling needs to reject a new booking that intersects an existing one, including bookings already in the table that collide with each other.
The task
Two half-open ranges overlap exactly when each starts before the other ends. A self-join with that test lists every pair of bookings for the same room that collide.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT a.booking_id, b.booking_id AS conflicts_with
FROM bookings a
JOIN bookings b
ON a.room_id = b.room_id
AND a.booking_id < b.booking_id
AND a.starts_at < b.ends_at
AND b.starts_at < a.ends_at
ORDER BY a.booking_id, b.booking_id;
它的運作方式
The pair of strict inequalities is the complete overlap test for half-open ranges [start, end): no need to enumerate the contained, left-overlap and right-overlap cases separately. Touching ranges (one ends exactly when the other starts) do not conflict, which is what strict < gives you. a.booking_id < b.booking_id lists each pair once. To check one new booking before inserting it, keep the same test with parameters: starts_at < :new_end AND ends_at > :new_start. A NULL end date makes the comparison unknown, so treat open-ended bookings with COALESCE(ends_at, a far-future date).
Variations
PostgreSQL: range types and the && operator
PostgreSQLSELECT a.booking_id, b.booking_id AS conflicts_with
FROM bookings a
JOIN bookings b
ON a.room_id = b.room_id
AND a.booking_id < b.booking_id
AND tsrange(a.starts_at, a.ends_at) && tsrange(b.starts_at, b.ends_at);
Questions that come up
How do I include boundary-touching ranges?
Use <= instead of < in both comparisons to treat ranges that merely touch as overlapping. Most scheduling domains want the strict version so back-to-back bookings remain legal. On PostgreSQL an exclusion constraint (EXCLUDE USING gist (room_id WITH =, tsrange(starts_at, ends_at) WITH &&), with btree_gist installed) rejects overlapping inserts outright.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.