Merge bookings into occupied periods
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
For each room, merge bookings that overlap or touch (one ends on the day the next starts) into one occupied period. Return the room, the first check_in and the last check_out of every period.
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
This is gaps and islands on date ranges. The running maximum of check_out over all earlier bookings is needed, not just the previous row: a short booking inside a long one would otherwise look like the end of the period. A running sum of the period starts numbers the periods, and MIN and MAX give their limits.
A hint if you get stuck
Sort a room's bookings by check_in. A new period starts when a booking begins after the latest check_out seen so far.
Background you need
Common mistakes on this exercise
- Compares with the previous row only: a short booking inside a longer one splits the period.
- With >= two bookings that touch are kept as separate periods.
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 Interview classics
- Third highest salary
- Second highest salary per department
- Earns more than the manager
- Departments above average
- Salary against the department average
- Pivot the statuses
- Repeat purchase rate
- Median salary
- Orders in consecutive months
- Runs of the same status
- Cohort retention
- Products bought together
- First order not paid
- A month with no sales still shows up (generate_series)
- Daily active users
- Monthly active users
- Funnel: users at each step
- Signup to purchase conversion
- New and returning users per day
- Day-1 retention
- Retention curve
- Sessions per user (30-minute rule)
- Rolling 7-day active users
- Longest streak of active days
- Monthly churn rate
- Reactivated subscribers
- Peak number of bookings at once