Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 96/ 160
05. Window Functions & Analytical SQL

Streak Detection & Consecutive Day Login Queries

Detect consecutive-day streaks using date differences and island grouping.

AdvancedStreaks · Consecutive Days3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Line up the days someone was active, start a new streak whenever there's a gap, then count each streak.

Think of it like…

Counting how many days in a row you've watered a plant: each day you watered it continues the count, a day you forgot resets it, and today's number is your current streak.

Where you’ve seen it

A language-learning app shows each user's current streak. The query converts lesson timestamps to the user's local date, keeps one row per user per day, flags a new streak when the gap from the previous day is more than 1 day, numbers the streaks with a running SUM, and returns the streak whose last day is today or yesterday. A paid "streak freeze" is handled by allowing a 2-day gap when a freeze was used.

Words you’ll hear

Change flag
1 when a row starts a new streak (gap too large), else 0.
Streak id
A running SUM of change flags; constant within each streak.
Current streak
The streak whose last day is today or yesterday, so it's still alive.
Local date
The activity date in the user's time zone, not UTC.

Visual diagram

Loading interactive diagram

Theory & example queries

The change-flag method

Start from one row per user per active day, computed in the user's time zone: (occurred_at AT TIME ZONE u.tz)::date grouped by user and day. Then CASE WHEN day - LAG(day) OVER w = 1 THEN 0 ELSE 1 END flags rows that start a streak (the first row has no previous day, so it's flagged too), and SUM(flag) OVER (w ROWS UNBOUNDED PRECEDING) turns flags into streak ids.

Group by user and streak id to get MIN(day) as the start, MAX(day) as the end and COUNT(*) as the length. Unlike the ROW_NUMBER subtraction trick, this method makes the continuation rule explicit, so variations are a one-line change: allow one missed day with <= 2, count weekdays only by joining a calendar, or build weekly streaks by truncating to weeks and comparing with 7 days.

All streaks per userQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  days AS (3    SELECT4      user_id,5      (occurred_at AT TIME ZONE tz)::date AS DAY6    FROM7      lessons8      JOIN users USING (user_id)9    GROUP BY10      1,11      212  ),13  flagged AS (14    SELECT15      user_id,16      DAY,17      CASE18        WHEN DAY - LAG(DAY) OVER (19          PARTITION BY20            user_id21          ORDER BY22            DAY23        ) = 1 THEN 024        ELSE 125      END AS new_streak26    FROM27      days28  ),29  ids AS (30    SELECT31      *,32      SUM(new_streak) OVER (33        PARTITION BY34          user_id35        ORDER BY36          DAY ROWS UNBOUNDED PRECEDING37      ) AS streak_id38    FROM39      flagged40  )41SELECT42  user_id,43  streak_id,44  MIN(DAY) AS start_day,45  MAX(DAY) AS end_day,46  COUNT(*) AS length47FROM48  ids49GROUP BY50  1,51  2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/51
3OutputInspect the representative rows, affected-row count, plan, or command status.
Detected streaks3 sample rows
Detected streaks
user_idstreak_idstart_dayend_daylength
712026-11-012026-11-033
722026-11-062026-11-072
912026-11-082026-11-081

Note: Assumes activity on these consecutive local dates; streak numbering restarts independently for each user.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Flag breaks with LAG, SUM the flags into ids, group by id.

Current streak, longest streak and edge cases

The current streak is the streak whose end_day is the user's local today or yesterday (yesterday because they may still be active later today); anyone else's current streak is 0. The longest streak is MAX(length) per user, and a leaderboard ranks users by it with DENSE_RANK. Compute "today" in each user's time zone too, or users east of UTC lose their streak early.

Watch the edge cases. Deduplicate before flagging, since two sessions on one day would otherwise create a gap of 0, which the = 1 test treats as a break. Daylight-saving changes don't matter once you're working with dates. For product analysis, streak length distributions (how many users reach 7, 30, 100 days) are usually more useful than averages.

Current streak per userQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.user_id,3  COALESCE(4    MAX(s.length) FILTER (5      WHERE6        s.end_day >= (now() AT TIME ZONE u.tz)::date - 17    ),8    09  ) AS current_streak10FROM11  streaks s12  JOIN users u USING (user_id)13GROUP BY14  s.user_id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Current streaks2 sample rows
Current streaks
user_idcurrent_streak
74
91

Note: Assumes the most recent qualifying streak for each shown user ends today or yesterday in that user’s timezone.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Current = ends today or yesterday in local time; dedupe days before flagging.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Prepare

One row per user per local day

Convert timestamps to the user's local date and deduplicate.

SQL at this stepReadable preview
1(occurred_at AT TIME ZONE tz)::date …2GROUP BY user_id,3  day
What to watch at this step
Duplicates
removed
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A streak is a run of consecutive active days (or weeks) for a user. The flexible way to find streaks is the change-flag method: compare each active day with the previous one using LAG, flag 1 when the gap is too big to continue the streak, and take a running SUM of the flags as a streak id. Grouping by streak id gives each streak's start, end and length, and the same query handles "current streak", weekly streaks and streaks that allow a missed day.

Why it matters: Learning apps, fitness trackers and games show streaks prominently because they drive daily habits, and product teams analyse them constantly. Interviewers ask for "current streak" and "longest streak" because they need deduplication, time zones, window functions and island grouping in one problem.

When to reach for it

  • Current and longest streak badges
  • Streak length distributions for product analysis
  • Consecutive-week or consecutive-month activity

When to avoid or be careful

  • Computing days in UTC for users in other time zones
  • Flagging before deduplicating to one row per day
  • Treating a streak that ended yesterday as broken

Change flags vs the ROW_NUMBER trick vs application code

LAG change flags + running SUM
Best for: Streaks with custom rules (allowed gaps, weekly, weekdays)

Strengths: The continuation rule is explicit and easy to change.

Watch out: Two window passes.

day − ROW_NUMBER() grouping
Best for: Strict consecutive-day streaks

Strengths: Short; one window function.

Watch out: Harder to adapt for gaps or weekly streaks.

Stored streak counter updated on activity
Best for: Showing a live streak in the app

Strengths: Instant reads.

Watch out: Needs care with time zones and missed days; SQL still needed for analysis.

Interview signals & numbers to know

When this topic comes up

  • “Find each user's current login streak”
  • “Longest consecutive-day streak”
  • “Users active three days in a row”
  • Gaps and islands
  • Engagement metrics

Benchmarks & rules of thumb

1 day -
the gap that continues a daily streak
today or yesterday -
when a streak is still current
2 -
window passes: LAG, then running SUM

Common mistakes & follow-ups

Common interview mistakes

  • Using UTC dates, so a user in India who practises at 1 a.m. local time gets the activity counted on the previous day.
  • Skipping deduplication, so two lessons on one day produce a gap of 0 and start a new streak.
  • Showing a current streak of 0 to everyone who hasn't practised yet today.

Likely interviewer follow-ups

  • How would you compute each user's current streak?
  • How would you allow one missed day without breaking a streak?
  • How would you find the longest streak across all users?
Interview tip: Mention local dates and deduplication before writing the window functions. Those two preparation steps are what make a streak query correct in production.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Streak Detection & Consecutive Day Login Queries with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Finding User First Purchase, Repeat Purchase & Time-Between-Orders
Next topic
Named Windows (WINDOW w AS (...)) for Cleaner Queries