Find the Double Booked Rooms
A booking covers starts_on up to but not
including ends_on. A booking that ends on 8 March and one
that begins on 8 March do not conflict.
Find every pair of bookings for the same room whose dates overlap:
room_ida_id— the lower booking id of the pairb_id— the higher booking id of the pair
Report each conflicting pair once, not twice, and never pair a booking with itself.
Order by room_id, then a_id, then
b_id.
Expected output
room_id | a_id | b_id
--------+------+-----
1 | 1 | 2
3 | 6 | 7
Editorial
SELECT a.room_id, a.id AS a_id, b.id AS b_id
FROM booking a
JOIN booking b
ON b.room_id = a.room_id
AND b.id > a.id
AND a.starts_on < b.ends_on
AND b.starts_on < a.ends_on
ORDER BY a.room_id, a_id, b_id;
The overlap test, and why it is this short
Two half-open ranges overlap if and only if each one starts before the other ends:
a.starts_on < b.ends_on AND b.starts_on < a.ends_on
Two conditions, no cases. People arrive at it the long way, by enumerating "a starts inside b, or b starts inside a, or a contains b, or b contains a", and then miss one — usually containment, which is why booking 7 sitting entirely inside booking 6 is in the seed. The short form covers all four because it is the negation of the only two ways ranges can miss: one ends before the other starts, or the other way round.
NOT (a.ends_on <= b.starts_on OR b.ends_on <= a.starts_on)
That is the same predicate. De Morgan takes you from one to the other, and either is fine to write — the long form is arguably easier to justify out loud, because "they don't overlap when one finishes before the other begins" is obviously exhaustive.
Strictly less than
<= reports bookings 2 and 3 as a conflict. Booking 2 covers
up to but not including 8 March and booking 3 starts on 8 March, so they share
no day. This is the direct consequence of the half-open convention, and it is
the convention worth defaulting to for exactly this reason: ranges defined as
[start, end) tile without gaps or double-counting, so
end of one is start of the next and no arithmetic is
needed to express "the next slot".
If the column means something else — a closed range where
ends_on is the last day occupied — then <= is
correct and the seed's bookings 2 and 3 really do conflict. The query cannot
tell you which; only the column's meaning can, and in a real schema that
meaning should be written down somewhere other than someone's memory.
b.id > a.id does two jobs
Without it the self-join returns each booking paired with itself — every
range overlaps itself — and each real pair twice, once in each direction.
b.id > a.id removes both at once: no self-pairs because the
comparison is strict, and one direction per pair because only one of
1 > 2 and 2 > 1 holds. It also makes the
statement's "lower id first" true by construction rather than by a later
sort.
Using b.id <> a.id instead is the usual near-miss: it
removes the self-pairs and keeps both directions, so the answer comes back
doubled.
Stopping it at write time
Everything above is a report on damage already done. PostgreSQL can refuse the second booking outright:
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE booking ADD CONSTRAINT booking_no_overlap
EXCLUDE USING gist (
room_id WITH =,
daterange(starts_on, ends_on, '[)') WITH &&
);
💡 An EXCLUDE constraint rejects a row if any existing row matches it
under the named operators — here, same room_id and overlapping
range. && is "overlaps"; '[)' declares the
range half-open, which is the same boundary choice the query made.
Three things this buys that the query cannot. It is enforced under
concurrency — two sessions booking the same room at the same instant cannot both
succeed, which a check-then-insert in application code cannot promise. It is
enforced for every writer, including the migration script and the person in
psql at 2am. And btree_gist is what lets the equality on
room_id share one index with the range overlap, so the check is a
lookup rather than a scan.
The cost is real: a GiST index to maintain on every write, an extension to install, and an error your application has to handle instead of a validation message it controls. For bookings, inventory, pricing periods and employment history, that trade is almost always worth taking — the alternative is discovering the overlap from a customer.
Scaling the query
The self-join is O(n²) within each room in the worst case. An index on
(room_id, starts_on) lets the planner cut it down, because for a
given a the candidate b rows are a contiguous range,
and the daterange-plus-GiST form above does better still:
SELECT a.room_id, a.id, b.id
FROM booking a JOIN booking b
ON b.room_id = a.room_id AND b.id > a.id
AND daterange(a.starts_on, a.ends_on, '[)') &&
daterange(b.starts_on, b.ends_on, '[)');
Same answer, one operator instead of two comparisons, and indexable. Worth knowing that the range type is a first-class value in PostgreSQL and not just a constraint trick.
What an interviewer is checking
The two-comparison overlap test, and whether you ask what
ends_on means before writing it. Volunteering the
EXCLUDE constraint is what turns a query answer into a design
answer, and the follow-up is almost always "how would you prevent this" — so the
constraint is the question, not a bonus.
booking
7 rows
| idinteger | room_idinteger | starts_ondate | ends_ondate |
|---|---|---|---|
| 1 | 1 | 1709251200000000 | 1709596800000000 |
| 2 | 1 | 1709510400000000 | 1709856000000000 |
| 3 | 1 | 1709856000000000 | 1710028800000000 |
| 4 | 2 | 1709251200000000 | 1709337600000000 |
| 5 | 2 | 1709596800000000 | 1709683200000000 |
Showing 5 of 7 rows.
room
3 rows
| idinteger | nametext |
|---|---|
| 1 | Blue |
| 2 | Green |
| 3 | Red |