KatInterview

Analyzing User Activity and Engagement Patterns with SQL

SQL & DataModel answer
MediumModel answerSQL & Datasqljoinswindow-functions

Last updated

Write SQL queries to analyze user engagement, including identifying inactive users, calculating monthly aggregates, segmenting by usage frequency, and tracking retention.

You have two database tables representing a transportation service:

Schema:

users table - contains registered user information:

  • user_id BIGINT PRIMARY KEY
  • city VARCHAR NOT NULL

rides table - contains completed trip records:

  • ride_id BIGINT PRIMARY KEY
  • ride_date TIMESTAMP NOT NULL
  • ride_rating DECIMAL (can be NULL)
  • user_id BIGINT NOT NULL (references users.user_id)

Important Details:

  • Every user in the users table should be considered, even if they've never completed a trip
  • Use America/Los_Angeles timezone for all date operations and month calculations
  • Trip counts are based on row counts in the rides table
  • When calculating rating averages, NULL values should be excluded; if all ratings are NULL, the average can be NULL

Write SQL queries to solve these four problems:

Problem 1: Identify Dormant Users Find how many users completed zero trips during the period from July 1, 2024 through July 7, 2024 (both dates inclusive). Include users who have never taken any trip.

  • Output: inactive_user_count

Problem 2: Month-over-Month Summary For every calendar month that has trip activity, calculate the total number of trips and the mean rating (rounded to 2 decimals). Order results with most recent months first.

  • Output: month_start, total_rides, avg_ride_rating

Problem 3: Infrequent User Segmentation Count how many users in each city have completed at most one trip in their entire history. Include users who never took a trip.

  • Output: city, low_frequency_user_count

Problem 4: Activity-Based Cohort Analysis For each user, identify which calendar months they were active (had at least one trip). Number these months sequentially (1st active month, 2nd active month, etc.), skipping any months without activity. Then calculate the average rating for trips taken during users' 1st and 3rd active months, broken down by city. Compute the average across all individual trips, not per-user averages.

  • Output: city, active_month_number, avg_ride_rating
  • Only include rows for active_month_number 1 and 3

Hints

Hint 1

For counting users with no activity, consider starting your query from the users table and using a LEFT JOIN or NOT EXISTS pattern.

Hint 2

Convert timestamps to Pacific timezone once at the beginning using a CTE to avoid inconsistencies across different parts of your queries.

Hint 3

When numbering a user's active months while skipping inactive ones, DENSE_RANK is more appropriate than ROW_NUMBER or RANK.