Streaks, sessions and retention
Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 11:10 on Friday. The product team asks: "How many sessions did the app have, and do people come back?" The events table has a user and a timestamp on every click, but no session id and no "came back" flag. Your first query says 20 sessions. The real number is 35.
You'll learn to
- Split rows into islands with LAG, a flag and a running sum
- Turn clicks into 30-minute sessions
- Find streaks of days in a row with date minus row number
- Build a simple cohort retention table
Learn
A session: clicks, then a quiet gap
Nobody stores a session. The app writes one row per click, with a user and a timestamp, and that is all.
So you need a rule. The product team's rule is the usual one: clicks that follow each other closely belong together, and 30 quiet minutes end a session. The next click after that starts a new one.
Look at user 23 on 3 June. Twelve clicks, in three bursts: around 13:00, around 17:30 and around 19:00. Three sessions. Your eye finds them at once. The job is to make SQL find them.
User 23 on 3 June, in minutes after 13:00
A timeline: twelve clicks in three bursts, from 13:00 to 13:20, 17:31 to 17:41 and 18:53 to 19:09, with the gaps between bursts far longer than 30 minutes, so they form three sessions.
Read it left to right: each blue tick is a click, and each teal bar is a session. A dashed mark shows where 30 quiet minutes ran out, so the next click after it starts a new session. Rounded to whole minutes.
Look back, flag, add up
Rows sorted in time form islands, runs that belong together, separated by gaps. A session is an island of clicks. The pattern that finds islands is called gaps and islands, and it has three steps:
- Look back.
LAGbrings each click's previous timestamp alongside it. Subtract, and you have the gap. - Flag. Write 1 where a new island starts: the gap is too big, or there is no previous row. Write 0 otherwise.
- Add up. A running
SUMof the flags gives every row its island number.
After that it is ordinary GROUP BY. You know all three tools from Lesson 2.5.
User 23: twelve clicks become three sessions
The twelve clicks of user 23 on 3 June in time order: first the gap to the previous click is worked out, then a flag marks each session start, then a running sum of the flags numbers the sessions 1, 2 and 3.
Look back.
LAGputs the previous click's time next to each click, and you subtract. The first click has no previous one, so its gap is NULL.Flag. Write 1 where a session starts: the gap is over 30 minutes, or there is no previous click. Write 0 everywhere else. Three rows get a 1.
Add up. A running sum of the flags climbs by 1 at every start and stays put in between. That sum is the session number.
Read each row's small line: it gains one fact per step, first the gap, then the flag, then the session number.
Steps 1 and 2: the gap and the flag
SELECT user_id, event_id, event_ts,
event_ts - LAG(event_ts) OVER w AS gap,
CASE
WHEN LAG(event_ts) OVER w IS NULL
OR event_ts - LAG(event_ts) OVER w > INTERVAL '30 minutes'
THEN 1 ELSE 0
END AS new_session
FROM events
WHERE user_id = 23
WINDOW w AS (PARTITION BY user_id ORDER BY event_ts, event_id)
ORDER BY event_ts, event_id;
WINDOW w AS (...) names a window once so you can reuse it. event_id breaks ties between two clicks in the same second. Read down the new_session column: three 1s.
The trap: the first row. LAG is NULL on each user's first event, and NULL > INTERVAL '30 minutes' is not true. So a flag written without IS NULL gives the first session a 0, and every user loses one session. That was this morning's 20: 35 sessions, minus one for each of the 15 users. Also partition by user, or clicks from different people interleave, and break timestamp ties with an id.
Step 3: number the sessions and count them
WITH flagged AS (
SELECT user_id, event_id, event_ts,
CASE
WHEN LAG(event_ts) OVER w IS NULL
OR event_ts - LAG(event_ts) OVER w > INTERVAL '30 minutes'
THEN 1 ELSE 0
END AS new_session
FROM events
WHERE user_id IS NOT NULL
WINDOW w AS (PARTITION BY user_id ORDER BY event_ts, event_id)
),
numbered AS (
SELECT *,
SUM(new_session) OVER (
PARTITION BY user_id
ORDER BY event_ts, event_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS session_no
FROM flagged
)
SELECT user_id,
COUNT(DISTINCT session_no) AS sessions,
COUNT(*) AS events
FROM numbered
GROUP BY user_id
ORDER BY user_id;
15 signed-in users and 35 sessions in all. Anonymous clicks (no user_id) are left out: without an id there is no way to know which clicks belong together. Real trackers give every browser an anonymous id for exactly this reason.
Remember: look back with LAG, flag the starts with 1, add the flags up with a running SUM. The first row always starts an island.
Streaks: days in a row
The product team has a follow-up: who orders several days in a row? Customer 13 ordered on 8, 9, 10 and 11 June: a four-day streak. A streak is an island of consecutive days.
First reduce the data to one row per customer per day with SELECT DISTINCT. Then use a neat trick.
Number each customer's days with ROW_NUMBER(). Inside a run of consecutive days, the date goes up by 1 and the row number goes up by 1, so date minus row number stays the same. When a day is skipped, the date jumps by 2 but the row number by 1, and the difference changes.
Group by that difference, and every group is one streak.
Customer 13's order days
| day | rownumber | day minus rownumber | streak |
|---|---|---|---|
| 2025-06-05 | 1 | 2025-06-04 | A |
| 2025-06-06 | 2 | 2025-06-04 | A |
| 2025-06-08 | 3 | 2025-06-05 | B |
| 2025-06-09 | 4 | 2025-06-05 | B |
| 2025-06-10 | 5 | 2025-06-05 | B |
| 2025-06-11 | 6 | 2025-06-05 | B |
| 2025-06-14 | 7 | 2025-06-07 | C |
Read the third column: it stays the same inside a streak and changes at every skipped day. Its value means nothing. Only "same or different" matters.
Every streak of three days or more
WITH days AS (
SELECT DISTINCT customer_id, DATE(order_ts) AS day
FROM orders
),
labelled AS (
SELECT customer_id, day,
day - CAST(ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY day
) AS INT) AS streak_key
FROM days
)
SELECT customer_id,
MIN(day) AS first_day,
MAX(day) AS last_day,
COUNT(*) AS days_in_a_row
FROM labelled
GROUP BY customer_id, streak_key
HAVING COUNT(*) >= 3
ORDER BY days_in_a_row DESC, customer_id;
DISTINCT matters: customer 23 ordered twice on 11 June, and two rows for one day would break the arithmetic. The CAST(... AS INT) is there because ROW_NUMBER() returns a big integer (bigint), and Postgres only subtracts a plain INT from a date.
Do they come back?
Now the second half of the question. A cohort is a group of users who started at the same time: everyone whose first visit was 1 June. Retention asks what share of a cohort is active again 1, 2, 7 or 30 days later.
Three steps, all familiar by now:
- One row per user per active day (
DISTINCT). - Each user's cohort day: their first active day (
MIN). - Join the two, and count users per cohort and per "days later".
Divide each count by the size of the cohort, the "0 days later" count, and you have a retention rate.
Retention by first-visit day
WITH active AS (
SELECT DISTINCT user_id, DATE(event_ts) AS day
FROM events
WHERE user_id IS NOT NULL
),
cohorts AS (
SELECT user_id, MIN(day) AS cohort_day
FROM active
GROUP BY user_id
)
SELECT c.cohort_day,
a.day - c.cohort_day AS days_later,
COUNT(*) AS users
FROM cohorts c
JOIN active a ON a.user_id = c.user_id
GROUP BY c.cohort_day, days_later
ORDER BY c.cohort_day, days_later;
Eight users first came on 1 June. Five of them came back on 2 June and two on 3 June: 62.5% and 25% retention. Pivot days_later into columns (Lesson 2.2) and you have the classic retention grid.
The 1 June cohort, one and two days later
Three bars for the users whose first visit was 1 June: 8 users on the day itself, 5 of them active again on 2 June, and 2 active again on 3 June.
All three bars count the same eight people. Each bar divided by the first one is that day's retention rate.
Sessions from the raw JSON events, in DuckDB
import duckdb
sessions = duckdb.sql("""
WITH flagged AS (
SELECT user_id,
CASE
WHEN LAG(ts) OVER w IS NULL
OR ts - LAG(ts) OVER w > INTERVAL 30 MINUTE
THEN 1 ELSE 0
END AS new_session
FROM read_json_auto('data/events.jsonl')
WHERE user_id IS NOT NULL
WINDOW w AS (PARTITION BY user_id ORDER BY ts, event_id)
)
SELECT SUM(new_session) FROM flagged
""").fetchone()[0]
print("sessions:", sessions)
The app's raw export calls the timestamp ts. Same pattern, same 35 sessions. In real pipelines this runs on millions of events, in Spark or a warehouse, with exactly this SQL.
Under the hood: one sort, two windows
The session query has two windows: one for LAG, one for the running SUM. In Lesson 2.3, two windows meant two sorts. Not here.
Both windows use PARTITION BY user_id ORDER BY event_ts, event_id. So the plan sorts the events once, by user_id, event_ts, event_id, and stacks two WindowAgg steps on that one Sort. The lower one computes LAG. The upper one computes the running SUM. After the sort, each WindowAgg holds about one row per user at a time.
A window that needs a different order, by event_type or DESC, would add a second Sort.
The streak query works the same way: its DISTINCT is a Unique over a Sort on customer_id, day, and the ROW_NUMBER reuses that order.
The session query's plan
EXPLAIN (COSTS OFF)
WITH flagged AS (
SELECT user_id, event_id, event_ts,
CASE
WHEN LAG(event_ts) OVER w IS NULL
OR event_ts - LAG(event_ts) OVER w > INTERVAL '30 minutes'
THEN 1 ELSE 0
END AS new_session
FROM events
WHERE user_id IS NOT NULL
WINDOW w AS (PARTITION BY user_id ORDER BY event_ts, event_id)
)
SELECT user_id,
SUM(new_session) OVER (
PARTITION BY user_id
ORDER BY event_ts, event_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS session_no
FROM flagged;
Two WindowAgg lines, one Sort. The Filter: (user_id IS NOT NULL) sits on the scan, so anonymous clicks are dropped before they are sorted.
One sort feeds both windows
A plan tree: the scan of events filters out anonymous clicks, one sort orders them by user, time and id, the first window computes LAG, and the second window on top computes the running sum.
Read it from the bottom up: scan and filter, one sort, the LAG window, then the running sum on top. The amber Sort is the only one.
At scale, sessions are one big sort
On 192 clicks none of this matters. On 3 billion it is the whole job. Turning clicks into sessions is called sessionising, and it means sorting every event by user and time. Spark does the same work when it brings all of one user's clicks together (Module 12).
A sort too big for memory writes temporary files. A server can cap them with the setting temp_file_limit, and then the query stops with:
ERROR: temporary file size exceeds "temp_file_limit"
The fixes are ones a pipeline wants anyway. Sessionise one day at a time, carrying each user's last click across days. Filter before sorting. Or run it on an engine built to sort in parallel.
Numbers to remember
| What | Number or name | What it means |
|---|---|---|
| Session timeout | 30 minutes | The usual choice in web analytics tools, and the one used here |
| Signed-in users, sessions | 15 users, 35 sessions | One gap in the data, 46 minutes, lies between 30 and 60 minutes, so a 60-minute timeout gives 34 |
| Forgetting IS NULL | 20 sessions | Each of the 15 users loses the first session: 35 - 15 |
| The 1 June cohort | 8 users, then 5, then 2 | Day-1 retention 62.5%, day-2 retention 25% |
| tempfilelimit | -1 by default: no limit | When an admin sets it, a sort that spills past it fails with ERROR: temporary file size exceeds "tempfilelimit" |
| Windows in the session query | 2 WindowAgg steps, 1 Sort | Both use PARTITION BY userid ORDER BY eventts, eventid |
| Streaming events | Spark's sessionwindow | The same idea when events arrive as a stream (Module 15) |
What changed at SwiftKart
The product team gets both answers. The app had 35 sessions from 15 signed-in users, not 20. And of the eight users who first came on 1 June, five were back the next day.
The session query is saved with its three steps named, so the next person can read it: look back, flag, add up. The streak and retention queries sit beside it.
Every query in this module so far only read data. On Tuesday night a load crashed half-way, you ran it again, and the reporting table ended up with 160 orders. Lesson 2.7 is about changing data so that a second run is harmless.
In one line
Gaps and islands: LAG to look back, a flag where a new island starts (the first row too), a running SUM to number islands; date minus ROW_NUMBER labels streaks; retention counts each cohort again N days later.
Interview corner
How would you sessionise a clickstream in SQL?
Partition by user and order by timestamp with a tie-breaker. Use LAG to get the previous timestamp, flag 1 when it is NULL or the gap exceeds the timeout (say 30 minutes), and take a running SUM of the flags as the session number. Then group by user and session number for start, end, clicks and duration.
How do you find each user's longest streak of consecutive active days?
Reduce to one row per user per day, number the days per user with ROW_NUMBER(), and subtract it from the date: within a streak that difference is constant. Group by user and the difference to get each streak's length, then take the maximum per user.
How do you compute cohort retention?
Find each user's cohort, usually the date or week of first activity, with MIN. Join it back to distinct (user, active day) rows, compute the periods since the cohort start, and count distinct users per cohort and period. Divide by the cohort size for a rate, and pivot periods into columns for the familiar grid.
Your sessionisation query must run over 3 billion clicks a day. What dominates its cost, and how would you design it?
The sort: both windows need every click ordered by user, time and a tie-breaker, and after that the windows are a single pass holding one row per user. Sorting 3 billion rows spills to disk, so I would process one day at a time and carry each user's last click over the midnight boundary, so a session crossing midnight is not split; filter bots and anonymous clicks before the sort; and keep both windows on the same PARTITION BY and ORDER BY so there is only one sort. On Spark the same job is a shuffle by user_id, or session_window in streaming.