Querydrill

Level 3: Joins Exercise 69 of 161 Medium Self joins and pairs

Overlapping bookings

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

A booking occupies its room from check_in up to, but not including, check_out. Return every pair of bookings for the same room that overlap, as two ids with the lower id first. A booking that starts on the day another one ends does not overlap it.

bookings (9 rows)

idroomguestcheck_incheck_out
1ANoor2025-06-012025-06-05
2AOmar2025-06-042025-06-08
3APia2025-06-082025-06-10
4BQuinn2025-06-022025-06-06
5BRosa2025-06-032025-06-04
6BSven2025-06-102025-06-12
7CTara2025-06-052025-06-07
8AUma2025-06-152025-06-18
9BVik2025-06-052025-06-09

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

The overlap test is two comparisons: a starts before b ends, and b starts before a ends. It covers partial overlaps and one booking inside another. a.id < b.id returns each pair once and stops a booking from matching itself.

A hint if you get stuck

Two periods overlap when each one starts before the other one ends.

Background you need

Common mistakes on this exercise

  • With <= a booking that starts on the day another ends counts as an overlap.
  • No room condition: bookings in different rooms are paired.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More practice on the same topic

More exercises in Joins