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)
| id | room | guest | check_in | check_out |
|---|---|---|---|---|
| 1 | A | Noor | 2025-06-01 | 2025-06-05 |
| 2 | A | Omar | 2025-06-04 | 2025-06-08 |
| 3 | A | Pia | 2025-06-08 | 2025-06-10 |
| 4 | B | Quinn | 2025-06-02 | 2025-06-06 |
| 5 | B | Rosa | 2025-06-03 | 2025-06-04 |
| 6 | B | Sven | 2025-06-10 | 2025-06-12 |
| 7 | C | Tara | 2025-06-05 | 2025-06-07 |
| 8 | A | Uma | 2025-06-15 | 2025-06-18 |
| 9 | B | Vik | 2025-06-05 | 2025-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 exerciseMore practice on the same topic
More exercises in Joins
- Orders with customer names
- Customers who never ordered
- Revenue per country
- Everyone with a department
- Employee and manager
- Revenue per product
- Revenue per category
- Products never sold
- Headcount per department
- Orders per customer
- Most recent order per customer
- Products per order
- Customers from the same country
- Customers who never had a refund
- Employees who manage nobody
- Categories per customer
- Payroll per department
- Direct reports per manager
- Stack two lists with UNION ALL
- Keep both sides with a full join
- Products on each order as one text (string_agg)
- Customers whose every order is paid (bool_and)
- Revenue inflated by a join (fan-out)
- Not equal, and the rows with NULL
- Compare two tables (EXCEPT)