The Gaps and Islands problem is the defining advanced SQL interview test. Learn how to group consecutive rows (islands) and detect missing intervals (gaps) using the row number difference and lag techniques.
Key Takeaways at a Glance:
- •The Gaps and Islands problem classifies contiguous sequences (islands) and missing intervals (gaps).
- •The ROW_NUMBER difference trick: subtracting a continuous ROW_NUMBER() from a sequence value (date - rn) produces a constant group identifier for contiguous streaks.
- •Classic interview questions: consecutive user login streaks, contiguous hotel booking dates, active sensor uptime periods.
- •The Flag / Cumulative Sum approach marks island transitions with a conditional flag and applies a running SUM to form group IDs.