KatInterview

Dropping Ever-Free Companies Before Monthly YoY Signup Counts

SQL & DataModel answer
MediumModel answerSQL & Datasqlanti-joinnot-exists

Last updated

Rework a monthly new-customer and year-over-year report so companies listed in a free-plan table vanish from every month, using a duplicate-safe anti-join applied before aggregation.

Context

You already have a report that shows, for each calendar month, how many companies made their first-ever paid subscription that month, along with the same figure twelve months earlier and the year-over-year growth. Assume the following setup (rename to match your own version):

  • Subscriptions(company_id INT, subscription_date DATE): a company may have many rows.
  • Output, one row per month with empty months filled with zero:
columntype
monthDATE (first day of the month)
new_subscribersINT
prev_year_new_subscribersINT (NULL when no month exists 12 months earlier)
yoy_growth_pctNUMERIC (NULL when the baseline is missing or 0)

New requirement

A second table lists companies that were at some point given a free plan:

Free_Subs
+------------+
| company_id |
+------------+
| 2          |
| 5          |
+------------+

Change the report so that any company present in Free_Subs is treated as if it never existed.

Rules

  • A company that ever appears in Free_Subs must disappear from every month and from every derived YoY figure (both the current value and the baseline).
  • Keep the output column names and types unchanged.
  • The exclusion must happen before any aggregation, so excluded companies cannot influence first-subscription detection, the zero-filled month range, or the YoY baselines.
  • Free_Subs may contain duplicate company_id values. The query must not duplicate or resurrect rows because of that.
  • In SQL comments, briefly compare NOT EXISTS with LEFT JOIN ... IS NULL as ways to express this anti-join on a typical columnar OLAP engine.

Expected

Write the full query, explain why the filter location matters, and list the edge cases you considered.

Hints

Hint 1

Where is the exclusion defined: on companies or on monthly totals? Filter at that level, in the very first CTE, so nothing downstream ever sees an excluded company.

Hint 2

Think about what each anti-join form does when the right-hand table has duplicate keys or a NULL key. Compare NOT EXISTS, NOT IN and LEFT JOIN ... IS NULL, and consider where a condition placed in ON versus WHERE changes the result.

Hint 3

Derive the calendar spine from the already-filtered first-subscription data, and build YoY by self-joining the filtered monthly CTE on month minus one year. Then check every later join is at most one-to-one.