Cohort Engagement Metrics for Single-Category Users
SQL & DataModel answerLast updated
Filter users into mutually exclusive content-type cohorts, then compute activity counts, median active days, a 10-day threshold rate, and per-user average minutes.
Cohort Engagement Metrics for Single-Category Users
You have a product with two content types that interest you: "social" and "game". Your goal is to compare how deeply each type's dedicated audience engages with the platform.
Schema
users(user_id INT, signup_date DATE)
sessions(session_id INT,
user_id INT,
session_start TIMESTAMP,
session_end TIMESTAMP,
category VARCHAR,
duration_minutes INT)
Analysis window
Include only sessions where session_start falls on or between 2025-08-04 and 2025-09-01, inclusive.
Data quality rules
Before any analysis, discard sessions that have a NULL category or a duration_minutes value that is zero or negative.
Cohort definitions
Using only the cleaned, in-window sessions, classify each user into exactly one of two groups:
- social_only — at least one
'social'session and zero'game'sessions - game_only — at least one
'game'session and zero'social'sessions
Drop everyone else: users who appear in both categories, and users who only have sessions in other categories.
Metrics to compute (per cohort)
| Column | Definition |
|---|---|
users_count | Number of users in the cohort |
median_active_days | Median (across users) of each user's count of distinct calendar days that had at least one session |
pct_users_active_10_plus_days | Percentage (0–100 scale) of users in the cohort whose active-day count is ≥ 10 |
avg_minutes_per_active_day | For each user, divide their total duration_minutes by their active-day count; then average that ratio across users in the cohort |
Output
Return one row per cohort with the columns above, ordered by cohort.
cohort | users_count | median_active_days | pct_users_active_10_plus_days | avg_minutes_per_active_day
Sample data
users
| user_id | signup_date |
|---|---|
| 1 | 2025-07-15 |
| 2 | 2025-08-10 |
| 3 | 2025-08-20 |
| 4 | 2025-08-25 |
sessions
| session_id | user_id | session_start | session_end | category | duration_minutes |
|---|---|---|---|---|---|
| 101 | 1 | 2025-08-05 10:00:00 | 2025-08-05 10:30:00 | social | 30 |
| 102 | 1 | 2025-08-06 10:00:00 | 2025-08-06 10:20:00 | social | 20 |
| 103 | 2 | 2025-08-07 09:00:00 | 2025-08-07 10:00:00 | game | 60 |
| 104 | 2 | 2025-08-08 09:00:00 | 2025-08-08 09:45:00 | game | 45 |
| 105 | 3 | 2025-08-09 12:00:00 | 2025-08-09 12:10:00 | social | 10 |
| 106 | 3 | 2025-08-13 12:00:00 | 2025-08-13 12:10:00 | game | 10 |
| 107 | 4 | 2025-08-11 14:00:00 | 2025-08-11 14:30:00 | game | 30 |
User 3 has both a social and a game session, so they are excluded. The expected output from the sample is:
| cohort | users_count | median_active_days | pct_users_active_10_plus_days | avg_minutes_per_active_day |
|---|---|---|---|---|
| game_only | 2 | 1.5 | 0.00 | 41.25 |
| social_only | 1 | 2.0 | 0.00 | 25.00 |
Write a single PostgreSQL query (CTEs are fine) that produces this result for the given window.
Hints
Hint 1
Build the query in three layers: clean and restrict to the window first, roll up to one row per user second, assign cohorts and aggregate third. Classifying users before cleaning is a common mistake — a session outside the window should not disqualify someone from social_only.
Hint 2
For the date boundary, avoid BETWEEN on a TIMESTAMP column. '2025-09-01' casts to midnight, silently dropping everything that happened during the rest of that day. Use `session_start >= start AND session_start < start + INTERVAL '1 day'` applied to the day after your end date instead.
Hint 3
avg_minutes_per_active_day is the mean of a per-user ratio, not a global ratio. AVG(total_minutes / active_days) and SUM(total_minutes) / SUM(active_days) give different numbers; the spec asks for the first form. Also watch out for integer division: cast the numerator or denominator to NUMERIC before dividing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The query has three natural stages, each expressed as a CTE.
Stage 1 — clean and window. Restrict sessions to the target date range and drop any row with a NULL category or a non-positive duration. This is the only place data quality rules are applied, which means a bad game session never contaminates a social user's cohort assignment.
Stage 2 — per-user rollup. Group by user and compute four things: how many social sessions the user had, how many game sessions, how many distinct calendar days they were active, and their total minutes. The cohort label follows directly from the session counts.
Stage 3 — per-cohort aggregation. For each cohort compute users_count, the median of active_days, the share with 10 or more active days, and the average of the per-user minutes-per-day ratio.
Things worth raising before writing
The window is 29 days, not 28. August 4 through September 1 inclusive is 29 calendar days. A true 28-day window would end August 31. Call this out early; it shows you read carefully and it matters if someone is comparing cohorts week-over-week.
Timestamp vs. date boundary. session_start < '2025-09-02' is safer than session_start <= '2025-09-01'. The latter silently becomes <= '2025-09-01 00:00:00' and drops every session from the afternoon of the 1st.
Average of ratios vs. ratio of sums. The spec says: compute minutes/active_days per user, then average. That is AVG(total_minutes / active_days). The alternative, SUM(total_minutes) / SUM(active_days), weights heavy users more and produces a different number. These are not interchangeable.
Integer division. In PostgreSQL, 105 / 2 is 52, not 52.5. Cast to NUMERIC before dividing.
No division by zero. Every user who reaches the rollup stage has at least one valid in-window session, so active_days >= 1 always. You can state this rather than adding a guard.
The Query
WITH params AS (
SELECT DATE '2025-08-04' AS start_date,
DATE '2025-09-01' AS end_date -- inclusive
),
valid_sessions AS (
SELECT
s.user_id,
CAST(s.session_start AS DATE) AS activity_date,
LOWER(TRIM(s.category)) AS category,
s.duration_minutes
FROM sessions s
CROSS JOIN params p
WHERE s.session_start >= p.start_date
AND s.session_start < p.end_date + INTERVAL '1 day' -- safe inclusive end
AND s.category IS NOT NULL
AND s.duration_minutes > 0 -- also filters NULL durations
),
user_stats AS (
SELECT
user_id,
COUNT(*) FILTER (WHERE category = 'social') AS social_sessions,
COUNT(*) FILTER (WHERE category = 'game') AS game_sessions,
COUNT(DISTINCT activity_date) AS active_days,
SUM(duration_minutes) AS total_minutes
FROM valid_sessions
GROUP BY user_id
),
cohorted AS (
SELECT
user_id,
active_days,
total_minutes,
CASE
WHEN social_sessions > 0 AND game_sessions = 0 THEN 'social_only'
WHEN game_sessions > 0 AND social_sessions = 0 THEN 'game_only'
END AS cohort
FROM user_stats
)
SELECT
cohort,
COUNT(*) AS users_count,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY active_days) AS median_active_days,
ROUND(
100.0 * AVG(CASE WHEN active_days >= 10 THEN 1 ELSE 0 END), 2
) AS pct_users_active_10_plus_days,
ROUND(
AVG(total_minutes::NUMERIC / active_days), 2
) AS avg_minutes_per_active_day
FROM cohorted
WHERE cohort IS NOT NULL -- drops mixed-category and other-only users
GROUP BY cohort
ORDER BY cohort;
Trace on the sample data
| user | clean categories in window | cohort | active_days | total_min | min/day |
|---|---|---|---|---|---|
| 1 | social, social | social_only | 2 | 50 | 25.00 |
| 2 | game, game | game_only | 2 | 105 | 52.50 |
| 3 | social, game | excluded | — | — | — |
| 4 | game | game_only | 1 | 30 | 30.00 |
For game_only: median of {2, 1} = 1.5 (interpolated); avg min/day = (52.5 + 30.0) / 2 = 41.25. Matches the expected output.
Correctness notes
- Mutual exclusivity is guaranteed structurally: the two CASE branches each require the other category's count to be zero, so they cannot both match.
- PERCENTILE_CONT interpolates between the two middle values for an even-sized group.
PERCENTILE_DISCwould return an actual observed value instead — mention it as an alternative if the team prefers discrete output. - pct_users_active_10_plus_days is on a 0–100 scale here. If downstream systems expect a 0–1 fraction, drop the
100.0 *multiplier and say so when you deliver the query.
Complexity
One pass over sessions filtered by an index on session_start — O(N). The per-user aggregation with COUNT(DISTINCT) is O(N log N) in the worst case. The cohort-level median requires a sort within each cohort, O(U log U) for U qualifying users. Output is constant size.
Edge cases to mention
- Empty cohort. If no users qualify for one cohort the query returns no row for it. To always return both rows,
LEFT JOINfrom(VALUES ('social_only'), ('game_only')) AS c(cohort)andCOALESCE(users_count, 0). - Case and whitespace in category.
LOWER(TRIM(...))guards against'Social 'or'GAME'slipping through as a different value. - Sessions only outside the window. A user whose sole game session is dated before August 4 has zero game sessions after cleaning, so they can still qualify as
social_only. This is the correct behavior.