Dropping Ever-Free Companies Before Monthly YoY Signup Counts
SQL & DataModel answerLast 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:
| column | type |
|---|---|
month | DATE (first day of the month) |
new_subscribers | INT |
prev_year_new_subscribers | INT (NULL when no month exists 12 months earlier) |
yoy_growth_pct | NUMERIC (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_Subsmust 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_Subsmay contain duplicatecompany_idvalues. The query must not duplicate or resurrect rows because of that.- In SQL comments, briefly compare
NOT EXISTSwithLEFT JOIN ... IS NULLas 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The exclusion is defined per company, so it has to be applied at row level before anything is grouped. If you filter after aggregation, the excluded companies are already baked into the monthly counts and into the YoY baselines. Filtering in the final SELECT can only drop entire months. It cannot subtract a company from a month.
So the plan is:
- Build
eligible_subs: subscription rows whose company is not inFree_Subs. This is the only placeFree_Subsis referenced. - Compute each eligible company's first subscription month.
- Derive the calendar spine from those filtered first-subscription months.
- Count new subscribers per month, zero-filled.
- Self-join the monthly result on
month - 1 yearto get the baseline and growth.
Query (PostgreSQL)
-- Anti-join trade-offs on columnar OLAP engines (Snowflake, BigQuery, Redshift, Spark, Trino):
--
-- NOT EXISTS (used here)
-- + A true anti-join semantically; planners turn it into a hash/broadcast anti-join
-- (Free_Subs is small, so it is usually broadcast).
-- + Duplicate-safe: it only asks "is there any match?", so repeated IDs never
-- multiply rows.
-- + NULL-safe, unlike NOT IN, where a single NULL in Free_Subs empties the result.
--
-- LEFT JOIN ... WHERE f.id IS NULL
-- + Same result, and most modern optimizers rewrite it to the same anti-join.
-- - If the pattern is not recognized, the outer join is materialized first and
-- duplicate keys inflate the intermediate result. Hence the DISTINCT subquery.
-- - Fragile: moving the IS NULL test into ON, or selecting right-side columns,
-- silently changes the result.
--
-- In Spark SQL prefer LEFT ANTI JOIN. In all engines, confirm with EXPLAIN that
-- an anti-join node is used.
WITH eligible_subs AS (
SELECT s.company_id, s.subscription_date
FROM subscriptions s
WHERE NOT EXISTS (
SELECT 1
FROM free_subs f
WHERE f.company_id = s.company_id
)
),
first_sub AS (
SELECT company_id,
DATE_TRUNC('month', MIN(subscription_date))::date AS month
FROM eligible_subs
GROUP BY company_id
),
bounds AS (
SELECT MIN(month) AS lo, MAX(month) AS hi
FROM first_sub
),
months AS (
SELECT generate_series(lo, hi, INTERVAL '1 month')::date AS month
FROM bounds
),
monthly AS (
SELECT m.month,
COUNT(fs.company_id)::int AS new_subscribers
FROM months m
LEFT JOIN first_sub fs ON fs.month = m.month
GROUP BY m.month
)
SELECT cur.month,
cur.new_subscribers,
prev.new_subscribers AS prev_year_new_subscribers,
CASE
WHEN prev.new_subscribers IS NULL OR prev.new_subscribers = 0 THEN NULL
ELSE ROUND(100.0 * (cur.new_subscribers - prev.new_subscribers)
/ prev.new_subscribers, 2)
END AS yoy_growth_pct
FROM monthly cur
LEFT JOIN monthly prev
ON prev.month = (cur.month - INTERVAL '1 year')::date
ORDER BY cur.month;
An equivalent duplicate-guarded form of the first CTE:
SELECT s.company_id, s.subscription_date
FROM subscriptions s
LEFT JOIN (SELECT DISTINCT company_id FROM free_subs) f
ON f.company_id = s.company_id
WHERE f.company_id IS NULL
Why it is correct
- Total exclusion.
NOT EXISTSis checked for every subscription row, so every row of a free company is removed, including paid rows before or after the free one. "Ever received" therefore means gone from all months. - No re-inclusion. After
eligible_subs, nothing touchesFree_Subsor rawSubscriptionsagain.first_subis unique per company,monthsandmonthlyare unique per month, so no later join can fan out or bring excluded rows back. - Duplicate-safe.
company_id = 2listed three times behaves like once, because the predicate is existence-based. - Clean spine. Bounds come from filtered data, so the series does not extend to months that exist only because of an excluded company.
- Clean YoY. The baseline comes from the same filtered
monthlyCTE, so numerator and denominator both exclude free companies. - Self-join over
LAG(..., 12). It is correct even if the spine later becomes sparse.
Complexity
With S subscription rows, F free rows, M months, C eligible companies:
- Time: hash anti-join O(S + F), group-by O(S), spine and YoY joins O(C + M). Overall O(S + F + M).
- Space: O(F) for the hashed or broadcast free-ID set, plus O(C + M) for intermediates.
Edge cases
- NULL
company_idinFree_Subs: ignored byNOT EXISTS.NOT INwould return nothing at all. - All companies are free:
boundsis NULL, the spine is empty, and the output is empty. If the original report used a fixed date range, keep it and you get zero rows per month instead. - Free company with no subscriptions: no effect.
- Baseline of 0:
yoy_growth_pctis NULL, whileprev_year_new_subscribersstill shows 0. - First 12 months of the spine: no baseline row, so the previous-year column is NULL.
- Sample data: companies 2 and 5 vanish everywhere. A month whose only new subscriber was company 2 now shows 0, and the following year's growth for that month is NULL because the baseline is 0.
Common mistakes
- Filtering in the final
SELECT, or afterGROUP BY. - Using
NOT INagainst a column that may contain NULLs. - Putting the
IS NULLcheck in theONclause of a left join, which keeps every row. - Joining raw
Free_Subswithout deduplicating, which multiplies rows. - Building the month spine from unfiltered data, leaving phantom months.
- Excluding only the "free" rows of a company instead of the whole company.
Pandas equivalent
Same contract: drop excluded IDs first, then aggregate.
free = set(free_subs["company_id"].dropna())
elig = subs[~subs["company_id"].isin(free)]
first = (elig.groupby("company_id")["subscription_date"].min()
.dt.to_period("M").dt.to_timestamp())
monthly = (first.value_counts()
.reindex(pd.date_range(first.min(), first.max(), freq="MS"),
fill_value=0)
.rename_axis("month").rename("new_subscribers").reset_index())
prev = monthly.assign(month=monthly["month"] + pd.DateOffset(years=1)) \
.rename(columns={"new_subscribers": "prev_year_new_subscribers"})
out = monthly.merge(prev, on="month", how="left")
out["yoy_growth_pct"] = ((out.new_subscribers - out.prev_year_new_subscribers)
/ out.prev_year_new_subscribers.where(out.prev_year_new_subscribers != 0)
* 100).round(2)
Using a set and isin is naturally duplicate-safe, and the filter runs before the group-by, mirroring the SQL.