Listening Sessions

A music streaming service wants to know how its listeners use the app. Group each listener's plays into sessions: plays are sorted by played_at, and a new session starts with the listener's first play and with every play that comes more than 30 minutes after that listener's previous play. A gap of exactly 30 minutes stays in the same session.

A session's length is the time from its first play to its last play, in minutes (a one-play session lasts 0 minutes).

Return one row per listener who has at least one play: listener_id, session_count, and avg_session_minutes, the average session length rounded to 1 decimal place. Any row order. Note that play_id is not guaranteed to follow time order.

Tables

track_plays — One row per track started.

ColumnTypeDescription
play_id (key)INTEGERUnique id, assigned on upload, so not necessarily in time order
listener_idINTEGERListener who started the track
track_idINTEGERTrack that was played
played_atTEXTWhen the track started, 'YYYY-MM-DD HH:MM:SS'

Example

track_plays

play_idlistener_idtrack_idplayed_at
173012026-02-10 08:00:00
273022026-02-10 08:04:00
373152026-02-10 08:34:00
473012026-02-10 09:10:00
591202026-02-10 21:00:00
691212026-02-10 21:20:30
791222026-02-10 22:00:00
891232026-02-10 22:15:00
945552026-02-11 07:30:00

Expected output

listener_idsession_countavg_session_minutes
410
7217
9217.8

Rows may be returned in any order. Your query also runs against hidden datasets with tricky edge cases.

SQL Path · Product Analytics · problem 66 of 70 · SQLite

Look at each play next to the previous play of the same listener: LAG(played_at) OVER (PARTITION BY listener_id ORDER BY played_at).
Flag a play with 1 when it starts a session (no previous play, or a gap over 1800 seconds) and 0 otherwise. unixepoch() turns a timestamp into seconds.
A running SUM of that flag per listener numbers the sessions. Group by listener and session number to get each session's first and last play.
Divide seconds by 60.0, then average per listener and round.

The idea

Sessionization is a two-step window pattern: flag the boundaries, then turn the flags into ids.

Flag. For each play, LAG(played_at) partitioned by listener and ordered by time gives the previous play of the same listener. The play starts a session if there is no previous play or the gap unixepoch(played_at) - unixepoch(prev_at) is greater than 1800 seconds. Strictly greater, so exactly 30 minutes stays in the session.

Number. A running SUM of the flag over the same window gives 1 for the first session, 2 after the next boundary, and so on. Every play now carries (listener_id, session_no).

Measure. Group by that pair: MAX - MIN of the timestamps is the session length; divide by 60.0 so partial minutes survive. Then group by listener for the count and the rounded average.

The alternative does it without windows: a play starts a session when no earlier play of the listener lies within the previous 30 minutes, and each play is assigned to the latest start at or before it.

Solution

WITH ordered AS (
  SELECT listener_id, played_at,
         LAG(played_at) OVER (PARTITION BY listener_id ORDER BY played_at) AS prev_at
  FROM track_plays
),
flagged AS (
  SELECT listener_id, played_at,
         CASE WHEN prev_at IS NULL OR unixepoch(played_at) - unixepoch(prev_at) > 1800 THEN 1 ELSE 0 END AS starts_session
  FROM ordered
),
numbered AS (
  SELECT listener_id, played_at,
         SUM(starts_session) OVER (
           PARTITION BY listener_id ORDER BY played_at
           ROWS UNBOUNDED PRECEDING
         ) AS session_no
  FROM flagged
),
sessions AS (
  SELECT listener_id, session_no,
         (unixepoch(MAX(played_at)) - unixepoch(MIN(played_at))) / 60.0 AS minutes
  FROM numbered
  GROUP BY listener_id, session_no
)
SELECT listener_id,
       COUNT(*) AS session_count,
       ROUND(AVG(minutes), 1) AS avg_session_minutes
FROM sessions
GROUP BY listener_id;

Another way

-- a play starts a session if the same listener has no play in the 30 minutes before it
WITH starts AS (
  SELECT DISTINCT p.listener_id, p.played_at AS start_at
  FROM track_plays AS p
  WHERE NOT EXISTS (
    SELECT 1 FROM track_plays AS q
    WHERE q.listener_id = p.listener_id
      AND q.played_at <  p.played_at
      AND q.played_at >= datetime(p.played_at, '-30 minutes')
  )
),
tagged AS (            -- each play belongs to the latest start at or before it
  SELECT p.listener_id, p.played_at,
         (SELECT MAX(s.start_at) FROM starts AS s
          WHERE s.listener_id = p.listener_id AND s.start_at <= p.played_at) AS start_at
  FROM track_plays AS p
),
sessions AS (
  SELECT listener_id, start_at,
         (unixepoch(MAX(played_at)) - unixepoch(start_at)) / 60.0 AS minutes
  FROM tagged
  GROUP BY listener_id, start_at
)
SELECT listener_id, COUNT(*) AS session_count, ROUND(AVG(minutes), 1) AS avg_session_minutes
FROM sessions
GROUP BY listener_id;

Why common answers fail

Uses >= 30 minutes, so a gap of exactly 30 minutes wrongly starts a new session.

WITH ordered AS (
  SELECT listener_id, played_at, LAG(played_at) OVER (PARTITION BY listener_id ORDER BY played_at) AS prev_at FROM track_plays
),
flagged AS (
  SELECT listener_id, played_at,
         CASE WHEN prev_at IS NULL OR unixepoch(played_at) - unixepoch(prev_at) >= 1800 THEN 1 ELSE 0 END AS starts_session
  FROM ordered
),
numbered AS (
  SELECT listener_id, played_at, SUM(starts_session) OVER (PARTITION BY listener_id ORDER BY played_at ROWS UNBOUNDED PRECEDING) AS session_no FROM flagged
),
sessions AS (
  SELECT listener_id, session_no, (unixepoch(MAX(played_at)) - unixepoch(MIN(played_at))) / 60.0 AS minutes FROM numbered GROUP BY listener_id, session_no
)
SELECT listener_id, COUNT(*) AS session_count, ROUND(AVG(minutes), 1) AS avg_session_minutes FROM sessions GROUP BY listener_id;

LAG has no PARTITION BY listener_id, so the gap is measured from another listener's play.

WITH ordered AS (
  SELECT listener_id, played_at, LAG(played_at) OVER (ORDER BY played_at) AS prev_at FROM track_plays
),
flagged AS (
  SELECT listener_id, played_at,
         CASE WHEN prev_at IS NULL OR unixepoch(played_at) - unixepoch(prev_at) > 1800 THEN 1 ELSE 0 END AS starts_session
  FROM ordered
),
numbered AS (
  SELECT listener_id, played_at, SUM(starts_session) OVER (PARTITION BY listener_id ORDER BY played_at ROWS UNBOUNDED PRECEDING) AS session_no FROM flagged
),
sessions AS (
  SELECT listener_id, session_no, (unixepoch(MAX(played_at)) - unixepoch(MIN(played_at))) / 60.0 AS minutes FROM numbered GROUP BY listener_id, session_no
)
SELECT listener_id, COUNT(*) AS session_count, ROUND(AVG(minutes), 1) AS avg_session_minutes FROM sessions GROUP BY listener_id;

Orders plays by play_id instead of played_at; ids are not chronological, so gaps are measured between the wrong plays.

WITH ordered AS (
  SELECT listener_id, played_at, LAG(played_at) OVER (PARTITION BY listener_id ORDER BY play_id) AS prev_at, play_id FROM track_plays
),
flagged AS (
  SELECT listener_id, played_at, play_id,
         CASE WHEN prev_at IS NULL OR unixepoch(played_at) - unixepoch(prev_at) > 1800 THEN 1 ELSE 0 END AS starts_session
  FROM ordered
),
numbered AS (
  SELECT listener_id, played_at, SUM(starts_session) OVER (PARTITION BY listener_id ORDER BY play_id ROWS UNBOUNDED PRECEDING) AS session_no FROM flagged
),
sessions AS (
  SELECT listener_id, session_no, (unixepoch(MAX(played_at)) - unixepoch(MIN(played_at))) / 60.0 AS minutes FROM numbered GROUP BY listener_id, session_no
)
SELECT listener_id, COUNT(*) AS session_count, ROUND(AVG(minutes), 1) AS avg_session_minutes FROM sessions GROUP BY listener_id;

Divides seconds by the integer 60, which truncates every session to whole minutes before averaging.

WITH ordered AS (
  SELECT listener_id, played_at, LAG(played_at) OVER (PARTITION BY listener_id ORDER BY played_at) AS prev_at FROM track_plays
),
flagged AS (
  SELECT listener_id, played_at,
         CASE WHEN prev_at IS NULL OR unixepoch(played_at) - unixepoch(prev_at) > 1800 THEN 1 ELSE 0 END AS starts_session
  FROM ordered
),
numbered AS (
  SELECT listener_id, played_at, SUM(starts_session) OVER (PARTITION BY listener_id ORDER BY played_at ROWS UNBOUNDED PRECEDING) AS session_no FROM flagged
),
sessions AS (
  SELECT listener_id, session_no, (unixepoch(MAX(played_at)) - unixepoch(MIN(played_at))) / 60 AS minutes FROM numbered GROUP BY listener_id, session_no
)
SELECT listener_id, COUNT(*) AS session_count, ROUND(AVG(minutes), 1) AS avg_session_minutes FROM sessions GROUP BY listener_id;

What the interviewer is checking

Sessionization is a staple for product analytics roles. It tests LAG with the right partition, the boundary rule and the running-sum trick for turning flags into group ids.

Mistakes to avoid

  • Forgetting PARTITION BY listener_id, so gaps cross listeners.
  • Ordering by an id column that is not chronological.
  • Using >= instead of > for the 30-minute rule.
  • Integer division when converting seconds to minutes.

Follow-ups to expect

  • Measure session length up to the end of the last track (add its duration from a tracks table).
  • Sessions per day of week (group the session start by strftime('%w', ...)).
  • Make the timeout configurable per platform (join a settings table and compare against its value).

In real work

Web and app analytics tools compute sessions this way from raw event streams to report session counts, session length and bounce rate.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url