Validate and Aggregate Subscription Event Data
SQL & DataModel answerLast updated
Profile a subscription events table to verify data integrity, then compute the earliest active date and most recent inactive date per subscription.
You're analyzing a subscription events dataset with the following schema:
subscriptions
+-----------------+---------+-------------+
| subscription_id | status | status_date |
+-----------------+---------+-------------+
| 101 | active | 2023-01-05 |
| 101 | inactive| 2023-03-10 |
| 102 | inactive| 2023-02-12 |
| 102 | active | 2023-04-01 |
+-----------------+---------+-------------+
Each row represents a subscription entering a particular status on a given date.
Part 1 (SQL): Before computing metrics, you need to validate the data quality. Write SQL queries that check common data integrity assumptions, such as:
- Are there any NULL values?
- What distinct values appear in the
statuscolumn? - Is
(subscription_id, status_date)a unique combination? - What status transitions occur (e.g., do subscriptions go directly from active to active)?
Part 2 (pandas): Create a function that returns one row per subscription_id with:
first_active_date: the earliest date the subscription had status'active'last_inactive_date: the most recent date the subscription had status'inactive'
If a subscription never had a particular status, the corresponding column should contain NaT.
Hints
Hint 1
Start by listing what properties you'd expect clean subscription data to have—then write a query for each assumption
Hint 2
Use window functions like LAG to detect consecutive identical statuses or unusual transitions
Hint 3
In pandas, filter the DataFrame by status before grouping; use min/max aggregation and reindex to handle missing states
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
What This Question Tests
This problem evaluates two skills:
- Data validation mindset: Do you verify assumptions about unfamiliar data before trusting it for analysis?
- Conditional aggregation: Can you compute per-entity metrics that depend on row-level filters efficiently?
Strong candidates articulate their assumptions explicitly, then systematically test each one.
Part 1: SQL Data Validation
Before computing any metrics, establish what the data actually contains. Common assumptions to verify:
statusonly contains'active'and'inactive'(no typos, casing issues, or whitespace)- No NULL values in key columns
(subscription_id, status_date)combinations are unique- Status changes follow expected patterns (no duplicate consecutive statuses)
Query 1: Basic Statistics and NULL Check
SELECT
COUNT(*) AS total_rows,
COUNT(DISTINCT subscription_id) AS unique_subscriptions,
SUM(CASE WHEN subscription_id IS NULL THEN 1 ELSE 0 END) AS null_ids,
SUM(CASE WHEN status IS NULL THEN 1 ELSE 0 END) AS null_statuses,
SUM(CASE WHEN status_date IS NULL THEN 1 ELSE 0 END) AS null_dates,
MIN(status_date) AS earliest_date,
MAX(status_date) AS latest_date
FROM subscriptions;
This gives you the scale and completeness of the dataset.
Query 2: Status Value Distribution
SELECT
status,
LENGTH(status) AS character_length,
COUNT(*) AS occurrences
FROM subscriptions
GROUP BY status, LENGTH(status)
ORDER BY occurrences DESC;
This catches issues like 'Active ' (trailing space) or 'ACTIVE' (wrong case) that would silently break downstream filters.
Query 3: Uniqueness Constraint Check
SELECT
subscription_id,
status_date,
COUNT(*) AS duplicate_count,
COUNT(DISTINCT status) AS distinct_statuses_on_date
FROM subscriptions
GROUP BY subscription_id, status_date
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;
If this returns any rows, you have duplicates. If distinct_statuses_on_date > 1, a subscription has conflicting statuses on the same date—a serious data quality issue.
Query 4: Transition Pattern Analysis
WITH status_sequence AS (
SELECT
subscription_id,
status,
status_date,
LAG(status) OVER (
PARTITION BY subscription_id
ORDER BY status_date
) AS previous_status
FROM subscriptions
)
SELECT
COALESCE(previous_status, 'START') AS from_state,
status AS to_state,
COUNT(*) AS transition_count,
COUNT(DISTINCT subscription_id) AS affected_subscriptions
FROM status_sequence
GROUP BY COALESCE(previous_status, 'START'), status
ORDER BY transition_count DESC;
Expected output shows:
START → activeandSTART → inactive: initial statesactive → inactiveandinactive → active: valid transitionsactive → activeorinactive → inactive: potential duplicates or snapshot-style logging
Query 5: Find Anomalous Subscriptions
WITH status_sequence AS (
SELECT
subscription_id,
status,
status_date,
LAG(status) OVER (
PARTITION BY subscription_id
ORDER BY status_date
) AS previous_status
FROM subscriptions
)
SELECT *
FROM status_sequence
WHERE status = previous_status
ORDER BY subscription_id, status_date;
This surfaces specific problematic rows for further investigation.
Part 2: pandas Aggregation
The goal is independent conditional aggregates per subscription:
- Filter to active rows → find minimum date → that's the first active date
- Filter to inactive rows → find maximum date → that's the last inactive date
Both results must be aligned on the complete set of subscription IDs.
Python Implementation
import pandas as pd
def validate_and_aggregate(df: pd.DataFrame) -> pd.DataFrame:
"""
Returns first active date and last inactive date per subscription.
Missing states result in NaT values.
"""
# Normalize and clean
working = df.copy()
working["status"] = working["status"].astype("string").str.strip().str.lower()
working["status_date"] = pd.to_datetime(working["status_date"], errors="coerce")
working = working.dropna(subset=["subscription_id", "status_date"])
# Get complete set of subscription IDs
all_subs = pd.Index(
working["subscription_id"].unique(),
name="subscription_id"
)
# Conditional aggregations
first_active = (
working[working["status"] == "active"]
.groupby("subscription_id")["status_date"]
.min()
.reindex(all_subs)
)
last_inactive = (
working[working["status"] == "inactive"]
.groupby("subscription_id")["status_date"]
.max()
.reindex(all_subs)
)
# Combine results
result = pd.DataFrame({
"first_active_date": first_active,
"last_inactive_date": last_inactive
}).reset_index()
return result.sort_values("subscription_id", ignore_index=True)
# Example usage
data = pd.DataFrame({
"subscription_id": [101, 101, 102, 102],
"status": ["active", "inactive", "inactive", "active"],
"status_date": ["2023-01-05", "2023-03-10", "2023-02-12", "2023-04-01"]
})
print(validate_and_aggregate(data))
Output:
subscription_id first_active_date last_inactive_date
0 101 2023-01-05 2023-03-10
1 102 2023-04-01 2023-02-12
Important Observations
For subscription 102, last_inactive_date (2023-02-12) precedes first_active_date (2023-04-01). This is correct given the data, but highlights a semantic issue: "last inactive date" doesn't necessarily mean "churn date." Subscription 102 is currently active, not churned. Always clarify metric definitions with stakeholders.
Why This Approach Works
- Boolean indexing isolates exactly the rows matching each status
- groupby + min/max computes the extreme date within each subscription's filtered rows
- reindex ensures every subscription appears in output, even if it never entered a particular state
- String normalization prevents silent failures from whitespace or casing variations
Complexity
- Time: O(n) for filtering and grouping, O(k log k) for final sort where k = number of subscriptions
- Space: O(n) for the working copy, O(k) for output
Common Mistakes
- Assuming clean data: Not checking for NULL values, typos, or duplicates before aggregating
- Missing subscriptions: Forgetting to reindex, causing subscriptions without a particular status to disappear from results
- Ignoring normalization: Not standardizing status values, causing
'Active'and'active'to be treated as different states - Misinterpreting results: Treating "last inactive date" as "churn date" without checking current status