Filter users by location and rank forums by activity
SQL & DataModel answerLast updated
Write SQL to classify users as US-based using profile and IP data, then identify the top forums by post volume and distinct contributors over a rolling 30-day window.
You have three tables representing an online discussion platform: users, posts, and forums.
Schema
users
user_idBIGINT, primary keyhome_country_codeVARCHAR, nullable (e.g. 'US', 'CA', 'GB')created_atTIMESTAMP
posts
post_idBIGINT, primary keyuser_idBIGINT, foreign key tousersforum_idBIGINT, foreign key toforumscreated_atTIMESTAMPip_country_codeVARCHAR, nullable (country derived from IP address)
forums
forum_idBIGINT, primary keyforum_nameVARCHAR
Requirements
Consider only posts created in the last 30 days relative to CURRENT_DATE. All timestamps are UTC.
Write two SQL queries:
Query 1: Classify users by US presence
A user is considered "US-based" if either:
- Their
home_country_codeequals 'US', or - At least 50% of their posts in the last 30 days have
ip_country_codeequal to 'US'
Return:
user_idus_flag(1 if US-based, 0 otherwise)us_post_share_30d(fraction of recent posts with US IP; null if the user has no recent posts)
Include all users, even those with no recent activity.
Query 2: Rank forums by activity
Identify the top 10 most active forums in the last 30 days, ranked by:
- Total post count (primary)
- Number of distinct users who posted (tiebreaker)
Return:
forum_idforum_namepost_count_30dactive_user_count_30d
Notes
- Handle null country codes appropriately
- Use standard SQL with CTEs and window functions as needed
- Normalize country codes (case-insensitive, trim whitespace)
Hints
Hint 1
Start by filtering posts to the 30-day window in a CTE—you'll reuse it for both queries
Hint 2
For the US flag, check the home country first, then calculate the IP-based ratio only when needed; watch out for division by zero
Hint 3
LEFT JOIN from users in Query 1 so users without recent posts still appear with null share
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both queries share a common foundation: isolate the 30-day post window once, aggregate at the appropriate granularity, then join back to dimension tables.
Query 1 works at user grain. Compute per-user post statistics from recent activity, then LEFT JOIN from the users table so every user appears. The classification logic combines profile data with behavioral signals.
Query 2 works at forum grain. Aggregate posts by forum, count distinct contributors, join to forums for names, and sort by the two-tier ranking criteria.
Key Decisions
Before writing code, clarify these assumptions with your interviewer:
-
30-day window definition: Posts where
created_at >= CURRENT_DATE - 30andcreated_at < CURRENT_DATE + 1. This includes today and the prior 30 calendar days. Adjust if the interviewer wants a different boundary. -
Null IP handling: A post with null
ip_country_codecounts toward the total post count but not toward US posts. The alternative—excluding null-IP posts from the denominator entirely—would inflate the ratio. State this choice explicitly. -
Null home country: Treat as non-US. Never allow
NULL = 'US'to silently determine the outcome. -
50% threshold: "At least 50%" means
>= 0.5, so a user with exactly half their posts from US IPs qualifies.
Solution
Query 1: US User Classification
WITH recent_posts AS (
SELECT
p.user_id,
CASE
WHEN UPPER(TRIM(p.ip_country_code)) = 'US' THEN 1
ELSE 0
END AS is_us_post
FROM posts p
WHERE p.created_at >= CURRENT_DATE - INTERVAL '30 days'
AND p.created_at < CURRENT_DATE + INTERVAL '1 day'
),
user_stats AS (
SELECT
user_id,
COUNT(*) AS total_posts,
SUM(is_us_post) AS us_posts
FROM recent_posts
GROUP BY user_id
)
SELECT
u.user_id,
CASE
WHEN COALESCE(UPPER(TRIM(u.home_country_code)), '') = 'US' THEN 1
WHEN s.total_posts > 0
AND s.us_posts * 1.0 / s.total_posts >= 0.5 THEN 1
ELSE 0
END AS us_flag,
CASE
WHEN s.total_posts > 0
THEN s.us_posts * 1.0 / s.total_posts
ELSE NULL
END AS us_post_share_30d
FROM users u
LEFT JOIN user_stats s ON s.user_id = u.user_id;
Why this works:
-
LEFT JOIN ensures completeness. Every user appears exactly once. Users with no recent posts have null stats, resulting in null share and a flag determined solely by
home_country_code. -
COALESCE prevents null comparison bugs.
NULL = 'US'evaluates to NULL (not false), which could incorrectly skip the first condition.COALESCEconverts null to empty string, forcing a clean false result. -
Guard against division by zero. The
total_posts > 0check prevents errors and ensures the share is only computed when meaningful. -
Multiply by 1.0 to force decimal division. In SQL,
3 / 4would produce0(integer division), silently classifying everyone as non-US. The* 1.0coerces to floating-point arithmetic. -
Normalization with UPPER and TRIM. Handles variations like
'us 'or'Us'consistently.
Query 2: Top Forums by Activity
WITH forum_activity AS (
SELECT
p.forum_id,
COUNT(*) AS post_count_30d,
COUNT(DISTINCT p.user_id) AS active_user_count_30d
FROM posts p
WHERE p.created_at >= CURRENT_DATE - INTERVAL '30 days'
AND p.created_at < CURRENT_DATE + INTERVAL '1 day'
GROUP BY p.forum_id
)
SELECT
f.forum_id,
f.forum_name,
a.post_count_30d,
a.active_user_count_30d
FROM forum_activity a
JOIN forums f ON f.forum_id = a.forum_id
ORDER BY
a.post_count_30d DESC,
a.active_user_count_30d DESC,
f.forum_id ASC
LIMIT 10;
Why this works:
-
Aggregate before joining. Computing metrics at forum grain first, then joining to
forums(which has one row per forum), prevents count inflation. -
COUNT(DISTINCT user_id) gives unique contributors. This correctly handles users who posted multiple times to the same forum.
-
Three-level sort ensures determinism. Post count first (primary metric), then distinct users (tiebreaker), then forum ID (for reproducible results across runs).
-
INNER JOIN filters to active forums. Only forums with recent posts appear. If you need to include forums with zero activity, use LEFT JOIN and COALESCE metrics to 0.
-
LIMIT 10 takes top entries. If ties at position 10 should all be included, replace LIMIT with
RANK() OVER (ORDER BY ...)and filterWHERE rnk <= 10.
Complexity
Let P = posts in the 30-day window, U = total users, F = forums with recent activity.
- Query 1: O(P) to scan and aggregate posts, O(U) to hash-join with users → O(P + U) time, O(U) space for aggregates.
- Query 2: O(P) to scan and aggregate, O(F log F) to sort forums → O(P + F log F) time.
COUNT(DISTINCT)requires O(P) space in worst case (every post from unique user-forum pair).
Index recommendation: An index on posts(created_at) or date-based partitioning converts the window filter from full table scan to efficient range scan.
Edge Cases
| Scenario | Handling |
|---|---|
| User with no recent posts | us_post_share_30d is NULL; us_flag determined by home_country_code only |
Both home_country_code and IP data are null | us_flag = 0 |
| All posts have null IP country | Share = 0.0 (denominator includes them, numerator does not) |
| Exactly 50% US posts | us_flag = 1 (threshold is >=) |
| Country codes with whitespace or mixed case | UPPER(TRIM(...)) normalizes them |
| Posts referencing deleted forums | Dropped by INNER JOIN; use LEFT JOIN to retain them |
| Fewer than 10 active forums | Query returns fewer rows, which is correct |
| Ties at 10th position | Current solution picks one arbitrarily; use RANK() to include all ties |
Alternative: pandas Implementation
If asked to implement in Python:
import pandas as pd
def classify_and_rank(users, posts, forums, today):
start = today.normalize() - pd.Timedelta(days=30)
end = today.normalize() + pd.Timedelta(days=1)
recent = posts[(posts['created_at'] >= start) & (posts['created_at'] < end)].copy()
# Query 1
recent['is_us'] = recent['ip_country_code'].fillna('').str.strip().str.upper().eq('US').astype(int)
stats = recent.groupby('user_id').agg(
total=('post_id', 'size'),
us_count=('is_us', 'sum')
).reset_index()
result = users[['user_id', 'home_country_code']].merge(stats, how='left', on='user_id')
result['us_post_share_30d'] = result['us_count'] / result['total']
home_us = result['home_country_code'].fillna('').str.strip().str.upper() == 'US'
ip_us = result['us_post_share_30d'].fillna(0) >= 0.5
result['us_flag'] = (home_us | ip_us).astype(int)
query1 = result[['user_id', 'us_flag', 'us_post_share_30d']]
# Query 2
activity = recent.groupby('forum_id').agg(
post_count_30d=('post_id', 'size'),
active_user_count_30d=('user_id', 'nunique')
).reset_index()
query2 = activity.merge(forums[['forum_id', 'forum_name']], on='forum_id') \
.sort_values(['post_count_30d', 'active_user_count_30d', 'forum_id'],
ascending=[False, False, True]) \
.head(10)
return query1, query2
The logic mirrors the SQL: filter once, aggregate at the right grain, join to preserve dimensionality.