Streak Detection & Consecutive Day Login Queries
Detect consecutive-day streaks using date differences and island grouping.
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
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.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
WITH days AS ( SELECT user_id, (occurred_at AT TIME ZONE tz)::date AS DAY FROM lessons JOIN users USING (user_id) GROUP BY 1, 2 ), flagged AS ( SELECT user_id, DAY, CASE WHEN DAY - LAG(DAY) OVER ( PARTITION BY user_id ORDER BY DAY ) = 1 THEN 0 ELSE 1 END AS new_streak FROM days ), ids AS ( SELECT *, SUM(new_streak) OVER ( PARTITION BY user_id ORDER BY DAY ROWS UNBOUNDED PRECEDING ) AS streak_id FROM flagged )SELECT user_id, streak_id, MIN(DAY) AS start_day, MAX(DAY) AS end_day, COUNT(*) AS lengthFROM idsGROUP BY 1, 2;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Detected streaks3 sample rows
| user_id | streak_id | start_day | end_day | length |
|---|---|---|---|---|
| 7 | 1 | 2026-11-01 | 2026-11-03 | 3 |
| 7 | 2 | 2026-11-06 | 2026-11-07 | 2 |
| 9 | 1 | 2026-11-08 | 2026-11-08 | 1 |
Note: Assumes activity on these consecutive local dates; streak numbering restarts independently for each user.
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.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
SELECT s.user_id, COALESCE( MAX(s.length) FILTER ( WHERE s.end_day >= (now() AT TIME ZONE u.tz)::date - 1 ), 0 ) AS current_streakFROM streaks s JOIN users u USING (user_id)GROUP BY s.user_id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Current streaks2 sample rows
| user_id | current_streak |
|---|---|
| 7 | 4 |
| 9 | 1 |
Note: Assumes the most recent qualifying streak for each shown user ends today or yesterday in that user’s timezone.
Key takeaway: Current = ends today or yesterday in local time; dedupe days before flagging.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
One row per user per local day
Convert timestamps to the user's local date and deduplicate.
(occurred_at AT TIME ZONE tz)::date …GROUP BY user_id, dayWhen 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
Strengths: The continuation rule is explicit and easy to change.
Watch out: Two window passes.
Strengths: Short; one window function.
Watch out: Harder to adapt for gaps or weekly streaks.
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?
Knowledge check
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.