Survey Response Rates and Rating Comparison by User Tenure
SQL & DataModel answerLast updated
Compute an overall survey response rate and compare average notification ratings across user tenure cohorts using SQL joins, aggregation, and bucketing.
Notification Survey Analysis
A mobile app prompts users to rate push notifications through in-app surveys. Two tables capture the relevant data:
survey_responses
| user_id | event_date | trigger_type | score |
|---|---|---|---|
| 101 | 2023-01-10 | notif_popup | 5 |
| 102 | 2023-01-11 | notif_popup | 3 |
| 101 | 2023-01-12 | notif_modal | 4 |
score is an integer from 1–5, or NULL if the user dismissed the survey without answering.
user_accounts
| user_id | signup_date | country |
|---|---|---|
| 101 | 2022-12-20 | US |
| 102 | 2023-01-05 | CA |
| 103 | 2023-01-07 | US |
Tasks
Part 1. Write a SQL query to compute the overall survey response rate — both at the impression level (what share of surveys shown received a response) and at the user level (what share of users who were shown a survey responded at least once).
Part 2. Write a SQL query to determine whether recently-registered users tend to rate notifications differently than long-tenured users. Group users into tenure buckets based on how many days had elapsed since signup at the time of the survey, then compute per-bucket response rate, average score, median score, and the number of distinct users.
Use PostgreSQL syntax. Briefly explain your assumptions, call out any edge cases, and state the time and space complexity of each query.
Hints
Hint 1
Before writing any SQL, decide what 'response rate' means: impressions with a non-NULL score divided by total impressions, not something you can read off a table that only logs answers. If the table logged only answered surveys, you would need a separate impressions table — say that out loud.
Hint 2
Measure tenure at survey time (event_date minus signup_date), not as of today. A user registered a year ago who answered in their first week was a new user when they rated. Use this per-row calculation as the basis for your bucket CASE expression.
Hint 3
After bucketing, compute both the event-level average (all rows) and the user-level average (one mean per user, then average those). They can diverge when a few users submit many responses in one bucket, and surfacing both shows the interviewer you understand Simpson's paradox-style distortions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Assumptions
State your assumptions before touching any SQL — this is where most candidates lose points.
- What counts as shown? Every row in
survey_responsesis one impression. A NULLscoremeans the user dismissed without answering; a non-NULLscoremeans they responded.COUNT(score)skips NULLs automatically, soCOUNT(score) / COUNT(*)gives the right ratio without any extra filtering. - What if the table only stores completed responses? Then you cannot compute a response rate from it alone — you need a separate impressions or sends table. Say this clearly. The queries below assume NULLs are present for dismissals.
- Impression-level vs. user-level rate. Impressions / shown is the standard product metric. User-level (share of surveyed users who answered at least once) is also useful because it removes the effect of users being surveyed many times.
- Tenure at survey time. Compute
event_date - signup_dateper row, not relative to today. One user can fall in different buckets across time, which is correct behavior. - Bucket boundaries. A defensible split for a consumer app: 0–7 days (brand new), 8–30 days, 31–90 days, 90+ days. Always check that your conclusion holds if you shift the cutoffs.
Part 1 — Overall Response Rate
-- Impression-level: answered / shown
SELECT
COUNT(*) AS surveys_shown,
COUNT(score) AS surveys_answered,
ROUND(
COUNT(score)::numeric / NULLIF(COUNT(*), 0),
4
) AS response_rate
FROM survey_responses;
-- User-level: users who answered at least once / users who were shown a survey
SELECT
ROUND(
COUNT(DISTINCT CASE WHEN score IS NOT NULL THEN user_id END)::numeric
/ NULLIF(COUNT(DISTINCT user_id), 0),
4
) AS user_response_rate
FROM survey_responses;
COUNT(column) ignores NULLs while COUNT(*) does not — their ratio is exactly what you want. The ::numeric cast prevents integer division truncating to zero. NULLIF(..., 0) handles an empty table without a division error.
Part 2 — Ratings by Tenure Cohort
WITH tenure_base AS (
SELECT
sr.user_id,
sr.trigger_type,
sr.score,
(sr.event_date - ua.signup_date) AS tenure_days
FROM survey_responses sr
JOIN user_accounts ua ON ua.user_id = sr.user_id
WHERE sr.event_date >= ua.signup_date -- drop rows with impossible tenure
),
bucketed AS (
SELECT
*,
CASE
WHEN tenure_days <= 7 THEN '1: 0-7d'
WHEN tenure_days <= 30 THEN '2: 8-30d'
WHEN tenure_days <= 90 THEN '3: 31-90d'
ELSE '4: 90d+'
END AS tenure_bucket
FROM tenure_base
),
user_means AS ( -- one average per user per bucket
SELECT tenure_bucket, user_id, AVG(score) AS user_avg
FROM bucketed
WHERE score IS NOT NULL
GROUP BY tenure_bucket, user_id
)
SELECT
b.tenure_bucket,
COUNT(*) AS surveys_shown,
COUNT(b.score) AS responses,
ROUND(COUNT(b.score)::numeric / NULLIF(COUNT(*), 0), 4) AS response_rate,
COUNT(DISTINCT b.user_id) AS distinct_users,
ROUND(AVG(b.score), 3) AS avg_score,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY b.score) AS median_score,
ROUND(STDDEV_SAMP(b.score), 3) AS score_stddev,
ROUND((
SELECT AVG(um.user_avg)
FROM user_means um
WHERE um.tenure_bucket = b.tenure_bucket
), 3) AS avg_of_user_means
FROM bucketed b
GROUP BY b.tenure_bucket
ORDER BY b.tenure_bucket;
Reading the sample data:
- User 102 answered 6 days post-signup → bucket
1: 0-7d, score 3. - User 101 answered at days 21 and 23 → bucket
2: 8-30d, scores 5 and 4, avg 4.5.
So in this tiny sample newer users score lower, not higher — but two users carry zero statistical weight.
Optional Python Equivalent
import pandas as pd
def tenure_response_analysis(
survey_responses: pd.DataFrame,
user_accounts: pd.DataFrame,
) -> pd.DataFrame:
df = survey_responses.merge(
user_accounts[["user_id", "signup_date"]], on="user_id", how="inner"
)
df["tenure_days"] = (
pd.to_datetime(df["event_date"]) - pd.to_datetime(df["signup_date"])
).dt.days
df = df[df["tenure_days"] >= 0]
df["bucket"] = pd.cut(
df["tenure_days"],
bins=[-1, 7, 30, 90, float("inf")],
labels=["0-7d", "8-30d", "31-90d", "90d+"],
)
return (
df.groupby("bucket", observed=True)
.agg(
surveys_shown=("user_id", "size"),
responses=("score", "count"),
distinct_users=("user_id", "nunique"),
avg_score=("score", "mean"),
median_score=("score", "median"),
)
.assign(response_rate=lambda t: t.responses / t.surveys_shown)
)
Complexity
Let S = survey rows, U = users.
- Part 1: O(S) time, O(1) space (two sequential scans). The
COUNT(DISTINCT)variant uses O(S) hash space in the worst case. - Part 2: The join is O(S + U) time and O(U) space. Grouping and aggregation are O(S). The median via
PERCENTILE_CONTrequires sorting within groups, making it O(S log S) overall. With an index onuser_accounts.user_idthe join is essentially O(S).
Edge Cases Worth Calling Out
- Integer division.
COUNT/COUNTin PostgreSQL truncates to an integer. Always cast the numerator tonumeric. - Survey predates signup. A data or timezone bug. The
WHERE event_date >= signup_dateguard drops these rows; log how many were removed. - Surveys with no matching user. An
INNER JOINsilently drops orphan rows. Verify the count with aLEFT JOIN ... WHERE ua.user_id IS NULLcheck before committing to the inner join. - Scale defined as 1–5. Confirm this with the data owner. A
0might encode "force-dismissed" and should be treated as NULL, not a real rating. - Timestamps vs. dates. If columns are timestamps,
event_date::date - signup_date::dateextracts the calendar-day difference cleanly. Mixing timestamp arithmetic with date arithmetic produces unexpected intervals. - Heavy responders skewing bucket averages. The
avg_of_user_meanscolumn guards against this. If it diverges fromavg_score, a small group of prolific users is driving the result — worth flagging to stakeholders.