Daily KPI Pipeline and Retention Cohorts in SQL
SQL & DataModel answerLast updated
Write SQL for a photo app: totals, top month, top followed user, daily KPI and follower-bucket tables in Los Angeles time, and week-1 retention cohorts.
Scenario
You own the analytics layer for a photo-sharing app. The raw tables are:
users(user_id, user_name, joined_at)photos(photo_id, user_id, created_at)follows(follower_user_id, followed_user_id, created_at)user_events(event_id, user_id, event_type, occurred_at)
Rules:
- Every timestamp is stored in UTC.
- Unless told otherwise, a "day" or "month" means a calendar day or month in
America/Los_Angeles. - A
followsrow means the follow began atcreated_atand stays active from then on. Nobody unfollows. - DAU for a day is the number of distinct users with at least one
user_eventsrow on that local day.
A dashboard reads from three pre-aggregated tables that you must fill:
kpi_daily_base(report_date, new_users, total_users_eod, dau, new_photos, total_follow_edges_eod)follower_bucket_daily(report_date, bucket, user_count), wherebucketis'0','1_2'or'3_plus'retention_cohort_daily(cohort_date, cohort_size, retained_w1_users)
Tasks
- Return the total number of users.
- Return the calendar month with the most signups.
- Return the user with the most followers.
- Populate the daily tables so the dashboard can show, per day:
- new users, and the change vs. 7 days earlier
- DAU, and the change vs. 7 days earlier
- new photos
- new photos per DAU, and the change vs. 7 days earlier
- total follower relationships
- the share of users with 0 followers, with 1-2 followers, and with 3+ followers
- Extend the work to compute week-1 retention. For users who signed up on local day
D, this is the share with at least one event on any local day fromD+7toD+13.
Write the SQL (any mainstream dialect is fine; say which one you use) and explain the design choices that keep the numbers correct.
Hints
Hint 1
Convert from UTC to the reporting timezone first, then cast to a date or truncate to a month. Truncating UTC and converting afterwards puts evening Pacific events on the wrong day.
Hint 2
Build a gapless list of dates (a date spine) and LEFT JOIN each daily count onto it with COALESCE to 0. Then 'row 7 back' really means 'the same weekday last week', and running totals are just window sums over the spine.
Hint 3
Follower counts never go down, so each user crosses the 1-follower and 3-follower thresholds exactly once. Find those two dates per user, count them per day, run a cumulative sum, and derive the three buckets by subtraction from total users.
Hint 4
For retention, deduplicate (user, active_date) pairs, then LEFT JOIN them to each user's signup date with the condition active_date BETWEEN cohort_date + 7 AND cohort_date + 13. Count distinct matched users against cohort size.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task looks like five queries but is really a small metrics pipeline. Four decisions determine whether the numbers are right:
- Timezone first. Convert UTC to
America/Los_Angeles, then take the date. This applies to signups, photos, follows and events alike. - A date spine. Quiet days must still produce a row. Without one,
LAG(x, 7)compares against whatever row happens to be seven rows back, which is silently wrong. - Cumulative values via window sums over daily deltas, rather than re-scanning history for every day.
- Follower buckets via milestone dates, not a users x days cross join (see Task 4).
The code is PostgreSQL and assumes timestamp columns holding UTC.
CREATE FUNCTION la_date(ts timestamp) RETURNS date
LANGUAGE sql IMMUTABLE AS $$
SELECT ((ts AT TIME ZONE 'UTC') AT TIME ZONE 'America/Los_Angeles')::date
$$;
Tasks 1-3
-- 1
SELECT COUNT(*) AS total_users FROM users;
-- 2: busiest signup month; RANK keeps ties
SELECT signup_month, signups FROM (
SELECT date_trunc('month', la_date(joined_at))::date AS signup_month,
COUNT(*) AS signups,
RANK() OVER (ORDER BY COUNT(*) DESC) AS rnk
FROM users GROUP BY 1) t
WHERE rnk = 1;
-- 3: most-followed user(s); DISTINCT guards against duplicate follow rows
SELECT user_id, user_name, followers FROM (
SELECT u.user_id, u.user_name,
COUNT(DISTINCT f.follower_user_id) AS followers,
RANK() OVER (ORDER BY COUNT(DISTINCT f.follower_user_id) DESC) AS rnk
FROM users u JOIN follows f ON f.followed_user_id = u.user_id
GROUP BY u.user_id, u.user_name) t
WHERE rnk = 1;
ORDER BY ... LIMIT 1 would return an arbitrary row on a tie. RANK() returns every tied winner. Say which behavior you chose.
Task 4: daily tables
KPI table. Compute per-day counts in separate CTEs, join them to the spine, and take running sums.
INSERT INTO kpi_daily_base
WITH bounds AS (
SELECT MIN(la_date(joined_at)) AS d0,
((now() AT TIME ZONE 'America/Los_Angeles')::date - 1) AS d1
FROM users),
spine AS (
SELECT g::date AS report_date
FROM bounds, generate_series(d0::timestamp, d1::timestamp, interval '1 day') g),
edges AS (
SELECT follower_user_id, followed_user_id, MIN(created_at) AS created_at
FROM follows GROUP BY 1, 2),
nu AS (SELECT la_date(joined_at) AS d, COUNT(*) AS n FROM users GROUP BY 1),
np AS (SELECT la_date(created_at) AS d, COUNT(*) AS n FROM photos GROUP BY 1),
nf AS (SELECT la_date(created_at) AS d, COUNT(*) AS n FROM edges GROUP BY 1),
act AS (SELECT la_date(occurred_at) AS d, COUNT(DISTINCT user_id) AS n
FROM user_events GROUP BY 1)
SELECT s.report_date,
COALESCE(nu.n, 0),
SUM(COALESCE(nu.n, 0)) OVER (ORDER BY s.report_date),
COALESCE(act.n, 0),
COALESCE(np.n, 0),
SUM(COALESCE(nf.n, 0)) OVER (ORDER BY s.report_date)
FROM spine s
LEFT JOIN nu ON nu.d = s.report_date
LEFT JOIN np ON np.d = s.report_date
LEFT JOIN nf ON nf.d = s.report_date
LEFT JOIN act ON act.d = s.report_date;
I stop at the last complete local day so a half-finished day never shows up as a dip.
Follower buckets. Because follows are never removed, a user's follower count only rises. So each user enters "at least 1" on the day of their first follower and "at least 3" on the day of their third. If you count those entry events per day and take a running sum, you get:
3_plus= running count of third-follower events1_2= running count of first-follower events minus3_plus0=total_users_eodminus running count of first-follower events
INSERT INTO follower_bucket_daily
WITH edges AS (
SELECT follower_user_id, followed_user_id, MIN(created_at) AS created_at
FROM follows GROUP BY 1, 2),
ranked AS (
SELECT followed_user_id, created_at,
ROW_NUMBER() OVER (PARTITION BY followed_user_id ORDER BY created_at) AS rn
FROM edges),
hits AS (
SELECT r.rn,
GREATEST(la_date(u.joined_at), la_date(r.created_at)) AS d
FROM ranked r JOIN users u ON u.user_id = r.followed_user_id
WHERE r.rn IN (1, 3)),
daily AS (
SELECT d,
COUNT(*) FILTER (WHERE rn = 1) AS h1,
COUNT(*) FILTER (WHERE rn = 3) AS h3
FROM hits GROUP BY d),
running AS (
SELECT k.report_date, k.total_users_eod,
SUM(COALESCE(daily.h1, 0)) OVER (ORDER BY k.report_date) AS ge1,
SUM(COALESCE(daily.h3, 0)) OVER (ORDER BY k.report_date) AS ge3
FROM kpi_daily_base k LEFT JOIN daily ON daily.d = k.report_date)
SELECT report_date, b.bucket, b.cnt
FROM running,
LATERAL (VALUES ('0', total_users_eod - ge1),
('1_2', ge1 - ge3),
('3_plus', ge3)) AS b(bucket, cnt);
The GREATEST clamp keeps a follow that predates the target's signup from pushing a user into a bucket before they exist.
Dashboard read. The spine has no gaps, so LAG(x, 7) is exactly "7 days earlier".
WITH k AS (
SELECT *, new_photos::numeric / NULLIF(dau, 0) AS photos_per_dau
FROM kpi_daily_base)
SELECT report_date,
new_users, new_users - LAG(new_users, 7) OVER w AS new_users_vs_7d,
dau, dau - LAG(dau, 7) OVER w AS dau_vs_7d,
new_photos, photos_per_dau,
photos_per_dau - LAG(photos_per_dau, 7) OVER w AS ppd_vs_7d,
total_follow_edges_eod
FROM k WINDOW w AS (ORDER BY report_date)
ORDER BY report_date;
Pivot the three buckets and divide each by total_users_eod (using NULLIF to avoid division by zero) for the percentage columns. If the product team wants percent change instead of absolute change, use (x - lag) / NULLIF(lag, 0).
Task 5: week-1 retention
INSERT INTO retention_cohort_daily
WITH cohort AS (
SELECT user_id, la_date(joined_at) AS cohort_date FROM users),
active AS (
SELECT DISTINCT user_id, la_date(occurred_at) AS active_date FROM user_events)
SELECT c.cohort_date,
COUNT(DISTINCT c.user_id) AS cohort_size,
COUNT(DISTINCT a.user_id) AS retained_w1_users
FROM cohort c
LEFT JOIN active a
ON a.user_id = c.user_id
AND a.active_date BETWEEN c.cohort_date + 7 AND c.cohort_date + 13
GROUP BY c.cohort_date;
The LEFT JOIN keeps cohorts with zero retained users. Deduplicating to (user, day) first keeps the join small.
Complexity
Everything is a handful of group-bys, sorts and window passes, so roughly O(N log N) over rows in the raw tables, plus O(days) for the spine. The milestone trick avoids an O(users x days) expansion.
Common mistakes
- Truncating in UTC, which shifts evening events onto the next day.
- Skipping the spine, so
LAG(…, 7)compares the wrong dates and zero-activity days vanish. - Counting duplicate follow rows, which inflates follower counts and edge totals.
- Using
LIMIT 1where ties matter. - Reporting retention for cohorts whose D+13 has not yet happened. Those rows understate retention, so flag or filter them when reading.
- Dividing by zero in per-DAU and percentage columns.