KatInterview

Filter users by location and rank forums by activity

SQL & DataModel answer
MediumModel answerSQL & Datasqlaggregationjoins

Last 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_id BIGINT, primary key
  • home_country_code VARCHAR, nullable (e.g. 'US', 'CA', 'GB')
  • created_at TIMESTAMP

posts

  • post_id BIGINT, primary key
  • user_id BIGINT, foreign key to users
  • forum_id BIGINT, foreign key to forums
  • created_at TIMESTAMP
  • ip_country_code VARCHAR, nullable (country derived from IP address)

forums

  • forum_id BIGINT, primary key
  • forum_name VARCHAR

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_code equals 'US', or
  • At least 50% of their posts in the last 30 days have ip_country_code equal to 'US'

Return:

  • user_id
  • us_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:

  1. Total post count (primary)
  2. Number of distinct users who posted (tiebreaker)

Return:

  • forum_id
  • forum_name
  • post_count_30d
  • active_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