Analyzing User Activity and Engagement Patterns with SQL
SQL & DataModel answerLast 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_idBIGINT PRIMARY KEYcityVARCHAR NOT NULL
rides table - contains completed trip records:
ride_idBIGINT PRIMARY KEYride_dateTIMESTAMP NOT NULLride_ratingDECIMAL (can be NULL)user_idBIGINT NOT NULL (references users.user_id)
Important Details:
- Every user in the
userstable should be considered, even if they've never completed a trip - Use
America/Los_Angelestimezone for all date operations and month calculations - Trip counts are based on row counts in the
ridestable - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
These queries test several SQL fundamentals: handling users who exist in one table but not another, timezone-aware date logic, aggregation with NULLs, and window functions for sequential numbering.
Core Principles
Timezone Normalization: Convert timestamps to Pacific time once in a CTE that all queries reference. This prevents subtle bugs where different parts of your query interpret the same timestamp differently, causing trips to land in wrong date buckets.
Handling Zero-Activity Users: Problems 1 and 3 require counting users who appear in users but have no matching rows in rides. This requires either LEFT JOIN with careful NULL handling or NOT EXISTS subqueries. Starting from users is essential.
Date Range Boundaries: Use half-open intervals (>= start AND < day_after_end) rather than BETWEEN, which can miss events occurring after midnight on the end date when working with timestamps.
Window Functions for Sequential Numbering: Problem 4 needs to number a user's active months while skipping inactive ones. DENSE_RANK() assigns the same rank to all rows with the same value (all trips in the same month get the same number) and doesn't skip numbers after ties.
Solution (PostgreSQL)
-- Reusable CTE for timezone conversion
WITH rides_pacific AS (
SELECT
ride_id,
user_id,
ride_rating,
(ride_date AT TIME ZONE 'UTC') AT TIME ZONE 'America/Los_Angeles' AS pacific_time
FROM rides
)
-- Query 1: Identify Dormant Users
SELECT COUNT(*) AS inactive_user_count
FROM users u
WHERE NOT EXISTS (
SELECT 1
FROM rides_pacific r
WHERE r.user_id = u.user_id
AND r.pacific_time >= TIMESTAMP '2024-07-01'
AND r.pacific_time < TIMESTAMP '2024-07-08'
);
-- Query 2: Month-over-Month Summary
SELECT
DATE_TRUNC('month', pacific_time)::date AS month_start,
COUNT(*) AS total_rides,
ROUND(AVG(ride_rating), 2) AS avg_ride_rating
FROM rides_pacific
GROUP BY DATE_TRUNC('month', pacific_time)::date
ORDER BY month_start DESC;
-- Query 3: Infrequent User Segmentation
WITH user_trip_counts AS (
SELECT u.user_id, u.city, COUNT(r.ride_id) AS total_trips
FROM users u
LEFT JOIN rides r ON r.user_id = u.user_id
GROUP BY u.user_id, u.city
)
SELECT
city,
SUM(CASE WHEN total_trips <= 1 THEN 1 ELSE 0 END) AS low_frequency_user_count
FROM user_trip_counts
GROUP BY city
ORDER BY city;
-- Query 4: Activity-Based Cohort Analysis
WITH user_month_ranks AS (
SELECT
r.user_id,
r.ride_rating,
DENSE_RANK() OVER (
PARTITION BY r.user_id
ORDER BY DATE_TRUNC('month', r.pacific_time)
) AS active_month_number
FROM rides_pacific r
)
SELECT
u.city,
m.active_month_number,
AVG(m.ride_rating) AS avg_ride_rating
FROM user_month_ranks m
JOIN users u ON u.user_id = m.user_id
WHERE m.active_month_number IN (1, 3)
GROUP BY u.city, m.active_month_number
ORDER BY u.city, m.active_month_number;
Why This Works
Query 1: NOT EXISTS returns true for users who have no matching rides in the date range. This naturally includes users with zero trips ever. A common mistake is using LEFT JOIN with the date filter in the WHERE clause, which converts it to an inner join and loses never-active users. If using LEFT JOIN, put the date condition in the ON clause and check for NULL in WHERE.
Query 2: DATE_TRUNC('month', ...) groups trips into calendar months. Sorting by the date value orders chronologically. COUNT(*) counts rows as specified. AVG() automatically excludes NULLs; if all ratings in a month are NULL, the result is NULL.
Query 3: The two-stage aggregation first counts trips per user, then sums users per city. Using COUNT(r.ride_id) instead of COUNT(*) is critical—with COUNT(*), a user with no trips still has one row from the LEFT JOIN, giving an incorrect count of 1 trip instead of 0.
Query 4: DENSE_RANK() numbers each distinct month value. Multiple trips in the same month get the same rank, and there are no gaps when months are skipped. For example, trips in January, March, and May receive ranks 1, 2, 3 (not 1, 3, 5). The final aggregation computes AVG() over individual trip rows, so a user with many trips in month 1 contributes proportionally more to that average—this is row-weighted, not user-weighted.
Complexity
Assuming U users and R rides:
- Query 1: O(U + R) with hash-based anti-join; can be O(U log R) with index seeks
- Query 2: O(R) for aggregation, O(M log M) for sorting M months (typically M << R)
- Query 3: O(U + R) for two aggregations with hash tables
- Query 4: O(R log R) for window function sorting, then O(R) for final aggregation
Common Pitfalls
Timezone Mistakes: Converting after filtering or grouping can shift events across day or month boundaries. A trip at 2 AM UTC on July 8 happened on July 7 in Los Angeles.
Date Range Off-by-One: Using <= '2024-07-07' with timestamps only captures midnight, missing the rest of the day.
LEFT JOIN Filter Placement: Date filters in WHERE eliminate NULL-extended rows, defeating the purpose of the outer join.
Wrong Window Function: ROW_NUMBER() numbers individual rows (giving different numbers to trips in the same month). RANK() skips numbers after ties (1, 1, 3 instead of 1, 1, 2).
NULL Handling: NOT IN with a subquery that can return NULL will return no rows. NOT EXISTS doesn't have this issue.
Aggregation Level: Problem 4 requires trip-level averaging, not averaging user averages. Each trip contributes one value to AVG().