Trust & Safety Exposure Queries on Daily Post Views
SQL & DataModel answerLast updated
Write three SQL queries over daily post views and per-policy risk scores: a windowed view threshold, nudity exposure share, and a monthly flagged-type mix.
Context
A Trust & Safety analytics team keeps two tables. Your job is to answer three exposure questions with SQL. The main difficulties are date windows, joins that can multiply rows, and deciding exactly what the denominator should count.
Table 1: daily_post_views (one row per user, post, and day)
user_idINTEGER: the user who viewed the postpost_idINTEGER: the post that was viewedviewsINTEGER: number of views that user generated on that post on that dayview_dateSTRING inYYYY-MM-DDformat, treated as a UTC date- Primary key: (
user_id,post_id,view_date)
Table 2: policy_risk (one row per post and policy)
post_idINTEGERpolicySTRING, such asSpam,Scam,Nudity, orHarassmentrisk_probDOUBLE: model-estimated probability that the post violates that policy- Primary key: (
post_id,policy)
A single post can have several policy_risk rows, one per policy. daily_post_views.post_id joins to policy_risk.post_id.
Assumptions
- Cast
view_datetoDATEwhen you need date arithmetic. - Define
as_ofas the maximumview_dateindaily_post_views. Do not use the current system date. - "Last 7 days" and "last 30 days" are inclusive windows that end on
as_of. - A post belongs to a policy when
risk_prob > 0.5. The comparison is strict. - Months come from the calendar month of
view_date.
Tasks
1. Posts with at least 10 views in the last 7 days. Count the distinct posts whose total views across all users and all dates in the window are at least 10. Apply the threshold to the post total after grouping. Output column: num_posts.
2. Nudity view prevalence in the last 30 days. A post counts as a Nudity post if it has a policy_risk row with policy = 'Nudity' and risk_prob > 0.5. Compute:
prevalence = views on Nudity posts in the last 30 days / views on all posts in the last 30 days
Output columns: nudity_views, total_views, nudity_view_prevalence.
3. Monthly policy distribution. For each calendar month and each policy, consider only post/policy pairs with risk_prob > 0.5 where the post received at least one view in that month. Report how many distinct posts were assigned to that policy in that month, and that policy's share of all flagged pairs in the month. Output columns: month, violation_type, flagged_post_count, distribution_pct.
Write standard SQL and note any dialect-specific functions you use.
Hints
Hint 1
Compute the anchor date once in a CTE. For an inclusive N-day window, the lower bound is as_of minus (N-1) days, not minus N days.
Hint 2
Filtering on a summed view count belongs in HAVING, not WHERE. For Q2, pre-reduce the risk table to one row per post before you join, or use EXISTS, so the join cannot multiply view rows.
Hint 3
For Q3, deduplicate to one row per (month, post) before counting. The percentage denominator is the total number of flagged pairs in the month, which you can get with a window SUM partitioned by month after grouping.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What the question tests
Each task hides a common SQL mistake:
- Q1 tests whether you filter on an aggregate in the right place and get the date window right.
- Q2 tests join fan-out.
policy_riskhas several rows per post, so a naive join repeats each post's views once per policy. - Q3 tests whether you aggregate at the correct grain and whether you know what the denominator counts.
Saying these traps out loud before you write any code earns credit.
Anchor the window
Compute the anchor once and reuse it:
WITH anchor AS (
SELECT MAX(CAST(view_date AS DATE)) AS as_of
FROM daily_post_views
)
For an inclusive window of N days, the condition is view_date BETWEEN as_of - (N-1) AND as_of. That gives - 6 for 7 days and - 29 for 30 days. The usual error is writing - 7 or - 30, which adds one extra day. In MySQL or Spark, use DATE_SUB. In Snowflake, use DATEADD.
Q1: Posts with at least 10 views in the last 7 days
WITH anchor AS (
SELECT MAX(CAST(view_date AS DATE)) AS as_of
FROM daily_post_views
),
post_totals AS (
SELECT v.post_id,
SUM(v.views) AS views_7d
FROM daily_post_views v
CROSS JOIN anchor a
WHERE CAST(v.view_date AS DATE) BETWEEN a.as_of - INTERVAL '6 days' AND a.as_of
GROUP BY v.post_id
HAVING SUM(v.views) >= 10
)
SELECT COUNT(*) AS num_posts
FROM post_totals;
Why it works:
- The table grain is user, post, and day, so no single row holds a post's total. You have to sum first.
HAVINGapplies the threshold to the post total. AWHERE views >= 10filter would keep only rows with at least 10 views, which is wrong.- After
GROUP BY post_id, each post appears once, soCOUNT(*)counts distinct posts.
Q2: Nudity view prevalence over the last 30 days
The trap: joining views to policy_risk on post_id alone repeats each view once for every policy row the post has. A post with four rows would count four times. Use one of two approaches:
- Reduce
policy_riskto a set of Nudity post IDs first. The primary key makes this one row per post. - Use
EXISTS, a semi-join, which never adds rows.
WITH anchor AS (
SELECT MAX(CAST(view_date AS DATE)) AS as_of
FROM daily_post_views
),
window_views AS (
SELECT v.post_id, v.views
FROM daily_post_views v
CROSS JOIN anchor a
WHERE CAST(v.view_date AS DATE) BETWEEN a.as_of - INTERVAL '29 days' AND a.as_of
),
nudity_posts AS (
SELECT DISTINCT post_id
FROM policy_risk
WHERE policy = 'Nudity'
AND risk_prob > 0.5
)
SELECT
SUM(CASE WHEN n.post_id IS NOT NULL THEN w.views ELSE 0 END) AS nudity_views,
SUM(w.views) AS total_views,
SUM(CASE WHEN n.post_id IS NOT NULL THEN w.views ELSE 0 END) * 1.0
/ NULLIF(SUM(w.views), 0) AS nudity_view_prevalence
FROM window_views w
LEFT JOIN nudity_posts n
ON w.post_id = n.post_id;
Why it works:
- LEFT JOIN keeps every view. The denominator must include views on posts with no risk rows at all. An inner join would drop those posts and overstate prevalence.
- No fan-out.
nudity_postshas at most one row per post, so the join keeps the row count ofwindow_views. - Integer division is avoided. Multiplying by
1.0forces decimal division. Without it, Postgres and SQL Server return 0. - Divide-by-zero is guarded.
NULLIFreturns NULL for an empty window, not an error. - Strict threshold. A post with
risk_probexactly 0.5 is not a Nudity post.
Q3: Monthly policy distribution
Plan:
- Reduce views to one row per (month, post), keeping only posts with views in that month.
- Join those rows to flagged pairs (
risk_prob > 0.5). - Count distinct posts per (month, policy).
- Divide each count by the month's total using a window function.
WITH active_month_posts AS (
SELECT DATE_TRUNC('month', CAST(view_date AS DATE))::DATE AS month,
post_id
FROM daily_post_views
GROUP BY 1, 2
HAVING SUM(views) > 0
),
flagged AS (
SELECT post_id, policy
FROM policy_risk
WHERE risk_prob > 0.5
),
counts AS (
SELECT m.month,
f.policy AS violation_type,
COUNT(DISTINCT m.post_id) AS flagged_post_count
FROM active_month_posts m
JOIN flagged f
ON m.post_id = f.post_id
GROUP BY m.month, f.policy
)
SELECT month,
violation_type,
flagged_post_count,
ROUND(100.0 * flagged_post_count
/ SUM(flagged_post_count) OVER (PARTITION BY month), 2) AS distribution_pct
FROM counts
ORDER BY month, violation_type;
Why it works:
- Dedupe before joining.
active_month_postsgives one row per (month, post). Counting raw view rows would overcount. - Denominator. The question asks for the share of flagged pairs, not distinct posts. A post flagged for both Spam and Scam appears once under each policy. Each (month, post, policy) combination is unique, so the per-month sum of
flagged_post_countequals the number of flagged pairs, and the shares total 100% per month. Dividing by distinct posts instead would let the shares exceed 100% combined. Say this out loud in the interview. - Window after aggregation.
SUM(...) OVER (PARTITION BY month)runs on the grouped rows, so no second self-join is needed. - Inner join is intended. Only flagged, viewed posts should appear in the output.
- Month key.
DATE_TRUNCreturns a real date.SUBSTR(view_date, 1, 7)returning'YYYY-MM'is an acceptable portable alternative.
Common mistakes
- Using
CURRENT_DATEinstead of the data's maximum date, which breaks on snapshot data. - Off-by-one window bounds (
- 7instead of- 6). - Filtering the sum with
WHEREinstead ofHAVING. - Joining the risk table without reducing it first, which inflates Q2's numerator and denominator.
- Dropping unscored posts with an inner join in Q2.
- Dividing with integer arithmetic.
Complexity
Let V be the row count of daily_post_views and S the row count of policy_risk.
- Q1 and Q2: one scan of views plus a hash aggregate or hash join. Time is O(V + S), and space is proportional to the number of distinct posts in the window.
- Q3: the grouped view step is O(V). The join yields at most (active month-posts × flagged policies per post) rows, and the window step sorts or hashes by month. Overall, roughly O(V + S + J log J), where J is the joined row count.
- At scale: partition or index the views table by
view_date, and indexpolicy_riskon(policy, risk_prob)or(post_id)so the filter and join stay cheap.