Querydrill

Level 5: Interview classics Exercise 126 of 161 Hard Gaps and islands

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)

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

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 exercise

More practice on the same topic

More exercises in Interview classics