Quick revision
The short answer
We order each room's bookings by start time and compute the latest end time seen so far before each row with MAX(end_ts) over the preceding rows. A booking starts a new busy interval when that running maximum is NULL or earlier than its start; a running SUM of that flag numbers the intervals, and GROUP BY room and interval with MIN(start_ts) and MAX(end_ts) merges them. In PostgreSQL 14 and later, range_agg(tstzrange(start_ts, end_ts)) does the merge directly, and an exclusion constraint can prevent overlaps in the first place.
What to remember
In this answer, we merged overlapping and touching bookings per room by ordering them by start time and computing MAX(end_ts) over the earlier rows, because comparing only with the previous booking's end fails when an earlier long booking covers later ones. A booking starts a new interval when that running maximum is NULL or earlier than its start; a running SUM of the flag numbers the intervals, and grouping by room and interval with MIN(start_ts) and MAX(end_ts) gives the busy periods. In PostgreSQL 14 and later, range_agg(tstzrange(start_ts, end_ts)) returns the merged intervals as a multirange, and an exclusion constraint with gist prevents overlaps in the first place.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We order each room's bookings by start time and compute the latest end time seen so far before each row with MAX(end_ts) over the preceding rows. A booking starts a new busy interval when that running maximum is NULL or earlier than its start; a running SUM of that flag numbers the intervals, and GROUP BY room and interval with MIN(start_ts) and MAX(end_ts) merges them. In PostgreSQL 14 and later, range_agg(tstzrange(start_ts, end_ts)) does the merge directly, and an exclusion constraint can prevent overlaps in the first place.
Why this question is asked
Merging overlapping intervals comes up whenever we work with time: room bookings, on-call shifts, machine downtime, user sessions. A calendar needs to show when a room is busy, not every individual booking, and capacity reports need the total busy time without double counting overlaps. Interviewers ask this coding question because the obvious solution, comparing each booking with the previous one, is wrong in a subtle way, and the right one shows real fluency with window functions. In this answer, we will set up bookings that overlap and touch, see why comparing with the previous row fails, build the running maximum solution step by step, use PostgreSQL's range_agg as an alternative, prevent overlaps with a constraint, and find free slots for the follow-up.
1Setting Up Bookings That Overlap and Touch
Room 1 has a long morning booking A, a short booking B inside it, a booking C that starts inside A and runs past it, a booking D that starts exactly when C ends, and a separate afternoon booking E.
Treating touching bookings as one interval is what the question asks: a room busy until 13:00 and again from 13:00 is busy without a break. So two bookings belong together when the later one starts at or before the busy interval's current end.
2Why Comparing With the Previous Row Fails
The first idea is to use LAG(end_ts) to compare each booking's start with the previous booking's end, and start a new interval when the start is later. Let us see what that does with our data.
Booking C starts at 11:30, after B's end at 11:00, so the previous-row comparison splits the interval there. But the room was never free at 11:30: A still runs until 12:00. The previous row is not the one that matters; what matters is the latest end of all earlier bookings in the interval. A long booking can cover many later short ones, which is exactly why we need a running maximum.
3The Running Maximum End
For each booking we compute the maximum end_ts of all earlier bookings in the same room, using a frame that stops one row before the current row. Ordering by start_ts and then end_ts makes the order deterministic when two bookings start together.
Notice that prev_max_end for C is 12:00, carried forward from A even though B came in between. That is the information the LAG version was missing.
4Flag, Number and Merge
Now we flag each booking that starts a new interval: the first booking of a room, where prev_max_end is NULL, and any booking that starts after prev_max_end. A running SUM of the flag gives each booking its interval number, because the number goes up by one at every new interval. Finally we group by room and interval number.
- Order bookings per roomby start_ts, end_ts
- Running max of earlier end timesMAX over rows before the current one
- Starts after that max, or first row?YesFlag 1: new intervalNoFlag 0: same interval
- Running sum of flagsgives the interval number
- Group by room and interval
MIN(start_ts),MAX(end_ts)
5 steps in order. Play them, or step through them one at a time.
MAX(end_ts) in the final step matters for the same reason as before: inside an interval, the last booking does not necessarily end last. The query uses only standard window functions, so it also runs on MySQL 8. With an index on (room_id, start_ts, end_ts) the rows arrive already in order and no sort is needed.
5The PostgreSQL Alternative: range_agg and Multiranges
PostgreSQL has range types, such as tstzrange for a range of timestamps with time zone, and since version 14 multiranges, sorted sets of non-overlapping ranges. The aggregate range_agg combines ranges into a multirange, merging any that overlap or are adjacent, and unnest turns the multirange back into rows.
tstzrange(start_ts, end_ts) uses the default bounds [), which include the start and exclude the end, so C [11:30, 13:00) and D [13:00, 14:00) are adjacent and range_agg merges them, matching our touching rule. The exclusion constraint goes further for systems that must never double book: it refuses any new booking whose range overlaps (&&) an existing booking of the same room, even when two requests arrive at the same moment. With the [) bounds, touching bookings are still allowed.
6Follow-up questions
How would you find free slots of at least 30 minutes between bookings?
Merge the bookings first, then compare each busy interval's end with the next interval's start: LEAD(busy_from) OVER (PARTITION BY room_id ORDER BY busy_from) - busy_to >= interval '30 minutes'. To include free time at the start and end of the working day, add the day's opening and closing as sentinel intervals, or in PostgreSQL subtract with multiranges: tstzmultirange(tstzrange(day_start, day_end)) - range_agg(...) gives the free ranges, which we filter by upper(r) - lower(r) >= interval '30 minutes'.
Why order by end_ts as well as start_ts?
Only to make the order deterministic when two bookings start at the same moment. The running maximum gives the same intervals either way, but a deterministic order makes the intermediate results reproducible and easier to debug.
What changes if touching bookings should stay separate?
Change the flag to start a new interval when start_ts >= prev_max_end instead of >. The range version has no simple switch for this, because range_agg always merges adjacent ranges, so for that rule the window query is the simpler choice.
7Conclusion
In this answer, we merged overlapping and touching bookings per room by ordering them by start time and computing MAX(end_ts) over the earlier rows, because comparing only with the previous booking's end fails when an earlier long booking covers later ones. A booking starts a new interval when that running maximum is NULL or earlier than its start; a running SUM of the flag numbers the intervals, and grouping by room and interval with MIN(start_ts) and MAX(end_ts) gives the busy periods. In PostgreSQL 14 and later, range_agg(tstzrange(start_ts, end_ts)) returns the merged intervals as a multirange, and an exclusion constraint with gist prevents overlaps in the first place.
Open with
This is a gaps and islands problem with intervals. Per room, I order bookings by start time, then end time. The key is to compute, for each booking, the maximum end time of all earlier bookings: max of end over partition by room, order by start and end, rows between unbounded preceding and one preceding.
Then, if they want more
A booking starts a new busy interval if that value is NULL, meaning it is the first, or if its start is after that maximum; starting exactly at the maximum counts as touching, so it stays in the same interval.
I turn that into a flag of one or zero with a case expression, then a running sum of the flag gives every booking an interval number. Finally I group by room and interval number and take min of start and max of end.
I would point out why the running maximum is needed: comparing only with the previous row's end is wrong, because an earlier long booking, say nine to twelve, can cover a short one from ten to eleven, and then a booking at eleven thirty would wrongly start a new interval.
In PostgreSQL 14 and later there is a shorter way: range agg of tstzrange of start and end returns a multirange with overlapping and adjacent ranges merged, and unnest gives the rows. And if the business must never double book, an exclusion constraint using gist with room equal and ranges overlapping prevents it at insert time.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 14, MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Table booking(room_id int, start_ts timestamptz, end_ts timestamptz) has overlapping...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/e6991a3d05/