KatInterview

Validate and Aggregate Subscription Event Data

SQL & DataModel answer
MediumModel answerSQL & Datasqlpandasdata-validation

Last 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 status column?
  • 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