SQL Interview & Case Lab
Back to Interview SQL Patterns

Consecutive Days, Sessions — Gaps and Islands

The pattern behind 'consecutive logins', 'session detection', 'streaks' — one of the SQL world's named techniques. FIND_VIDEO: search 'SQL gaps and islands consecutive days' — recommended channel: Itzik Ben-Gan / Modern SQL. Aim for 12 min or under.

4 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Introduction to Gaps and Islands — The playing card analogy illustrates sequential island groups and missing gap elements.
  2. Date Range Overlap Complexities — Sample data highlights challenges with overlapping and fully enclosed interval records.
  3. Lag Function and Row Numbering — Row numbering and the LAG function capture the previous interval boundary.
  4. Island Indicator and Running Total — A conditional start indicator combined with a running SUM assigns group IDs.
  5. Aggregation into Island Ranges — Grouping by island ID with MIN and MAX consolidates fragmented date ranges.
PDF notes

Frequently asked questions

Why is this problem harder than traditional discrete gaps and islands?

Discrete problems evaluate single integer steps, whereas date interval problems must handle overlapping boundaries and fully enclosed time spans.

Is the binary island start indicator strictly required in production queries?

No, you can embed the CASE condition directly inside the cumulative SUM window function without creating an intermediate column.

What happens if an interval is completely contained within an earlier interval?

Its start date will be earlier than the previous end date, correctly assigning it an indicator of 0 to keep it in the same island.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.