Calculating Monthly Theme Engagement and Revenue Trends in SQL
SQL & DataModel answerLast updated
Define usage growth metrics and write SQL to analyze monthly active users, new user acquisition, and discrete monthly revenue for custom app themes.
You are analyzing user engagement and monetization data for a custom theme platform. You are given two tables capturing user interactions and purchases for specific digital themes.
Schema
theme_usage
+-----------+------------+-------------+
| user_id | theme_name | created_at |
+-----------+------------+-------------+
| 101 | pirate | 2024-01-05 |
| 102 | pirate | 2024-01-06 |
| 101 | pirate | 2024-02-14 |
| 110 | pirate | 2024-02-20 |
| 103 | pirate | 2024-03-01 |
+-----------+------------+-------------+
theme_transactions
+-----------+------------+--------+
| order_id | created_at | amount |
+-----------+------------+--------+
| 1 | 2024-01-05 | 2.99 |
| 2 | 2024-01-06 | 2.99 |
| 3 | 2024-02-14 | 2.99 |
| 4 | 2024-02-20 | 2.99 |
| 5 | 2024-03-01 | 2.99 |
+-----------+------------+--------+
Objective
- Propose a meaningful metric to quantify month-over-month (MoM) growth in usage for the pirate theme. Write a SQL query that generates this metric aggregated by calendar month, alongside the percentage growth rate relative to the preceding month.
- Write a SQL query to calculate non-cumulative monthly revenue and transaction count specifically for the pirate theme (assume
theme_transactionscontains sales data for this theme), along with month-over-month revenue growth percentage.
Hints
Hint 1
Avoid using raw event counts as your primary usage metric, as power users can skew the trend. Consider Monthly Active Users (MAU) using COUNT(DISTINCT user_id).
Hint 2
Use DATE_TRUNC('month', created_at) to aggregate timestamps into calendar months.
Hint 3
To correctly calculate month-over-month growth when certain months might have zero activity, generate a complete series of continuous monthly dates.
Hint 4
Use NULLIF when calculating percentage changes to prevent division-by-zero runtime errors.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Standard Approach & Key Definitions
When asked to evaluate "usage growth," selecting the right aggregation standard is critical:
- Raw Row Count (Event Volume): Highly sensitive to power-user behavior. A single user activating a theme 50 times in a month will falsely mimic broad platform adoption.
- Monthly Active Users (MAU): Counts
COUNT(DISTINCT user_id)within each calendar month. This measures unique reach and product penetration. - First-Time Users (Acquisition): Measures new user adoption by flagging the minimum timestamp per user.
For product growth, MAU combined with Month-over-Month (MoM) growth % is the standard primary metric. Calculating first-time user acquisition alongside MAU provides deeper insight into whether growth is driven by retention or new acquisition.
Part 1: Monthly Active Users & Growth Rate
To ensure robustness against missing months (months where no usage occurs), we can generate a continuous calendar spine using generate_series.
WITH monthly_mau AS (
SELECT
DATE_TRUNC('month', created_at)::DATE AS month,
COUNT(DISTINCT user_id) AS active_users
FROM theme_usage
WHERE theme_name = 'pirate'
GROUP BY 1
),
user_first_seen AS (
SELECT
user_id,
DATE_TRUNC('month', MIN(created_at))::DATE AS first_month
FROM theme_usage
WHERE theme_name = 'pirate'
GROUP BY user_id
),
monthly_new_users AS (
SELECT
first_month AS month,
COUNT(1) AS new_users
FROM user_first_seen
GROUP BY 1
),
date_spine AS (
SELECT generate_series(
(SELECT MIN(month) FROM monthly_mau),
(SELECT MAX(month) FROM monthly_mau),
INTERVAL '1 month'
)::DATE AS month
)
SELECT
ds.month,
COALESCE(m.active_users, 0) AS active_users,
COALESCE(n.new_users, 0) AS new_users,
ROUND(
100.0 * (COALESCE(m.active_users, 0) - LAG(COALESCE(m.active_users, 0)) OVER (ORDER BY ds.month))
/ NULLIF(LAG(COALESCE(m.active_users, 0)) OVER (ORDER BY ds.month), 0),
1
) AS mau_mom_growth_pct
FROM date_spine ds
LEFT JOIN monthly_mau m ON ds.month = m.month
LEFT JOIN monthly_new_users n ON ds.month = n.month
ORDER BY ds.month;
Query Output for Sample Data
| month | active_users | new_users | mau_mom_growth_pct |
|---|---|---|---|
| 2024-01-01 | 2 | 2 | NULL |
| 2024-02-01 | 2 | 1 | 0.0 |
| 2024-03-01 | 1 | 1 | -50.0 |
Note: User 101 used the theme in both January and February. In February, total MAU remains 2 (Users 101 and 110), but new users drop to 1 (User 110).
Part 2: Non-Cumulative Monthly Revenue Trend
The requirement asks for discrete (non-cumulative) monthly revenue. We perform a standard temporal grouping using SUM() without a cumulative OVER (ORDER BY ...) running sum.
WITH monthly_rev AS (
SELECT
DATE_TRUNC('month', created_at)::DATE AS month,
SUM(amount) AS revenue,
COUNT(order_id) AS total_orders
FROM theme_transactions
GROUP BY 1
)
SELECT
month,
revenue,
total_orders,
ROUND(
100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0),
1
) AS revenue_mom_growth_pct
FROM monthly_rev
ORDER BY month;
Query Output for Sample Data
| month | revenue | total_orders | revenue_mom_growth_pct |
|---|---|---|---|
| 2024-01-01 | 5.98 | 2 | NULL |
| 2024-02-01 | 5.98 | 2 | 0.0 |
| 2024-03-01 | 2.99 | 1 | -50.0 |
Computational Complexity
- Time Complexity: $O(N \log N)$ where $N$ is the number of raw records in
theme_usageortheme_transactions. Grouping and distinct aggregations require sorting or hash-based grouping $O(N)$, while the window functionLAG()across $M$ distinct months runs in $O(M \log M)$ time. Since $M \ll N$, execution time is bounded by the initial aggregation scan. - Space Complexity: $O(U + M)$ where $U$ is the number of distinct user IDs tracking first-seen timestamps, and $M$ is the number of unique calendar months retained in hash tables and CTE memory structures.
Edge Cases & Interview Strategy
- Gaps in Activity Months: If no users engage during a specific month (e.g., zero usage in March), a standard
GROUP BYomits that row entirely. In that case,LAG()would evaluate the immediately preceding row (February) as if it were the previous contiguous month, producing erroneous MoM metrics. Using a calendar spine CTE (generate_series) prevents this gap. - Division by Zero: When transitioning from
0active users in month $T-1$ to $K$ active users in month $T$, calculating growth percentage involves dividing by zero. Wrap denominators inNULLIF(..., 0)to safely yieldNULLinstead of a SQL execution error. - Incomplete Current Month: Reporting on an ongoing calendar month distorts MoM performance downward. Clarify with the interviewer whether to exclude the active month (
created_at < DATE_TRUNC('month', CURRENT_DATE)). - Time Zone Alignment: Timestamps should be truncated after adjusting to the company's operational time zone (e.g.,
created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York').