topskill.dev
CoursesTracks
All courses/Data Analysis Using SQLSeparate zero retention from an unobserved period
Cohorts, funnels, and member segments
7 / 19
← Data Analysis Using SQL
○Define the row before the metric○Exercise: define the row before the metric○Profile missing values without hiding them○Exercise: profile missing values without hiding them○Group records by a business key○Exercise: Group records by a business key○Filter completed groups with HAVING○Exercise: Filter completed groups with HAVING✦Module Quiz
○Remove surrounding spaces with TRIM○Exercise: Remove surrounding spaces with TRIM○Normalize case with LOWER○Exercise: Normalize case with LOWER○Mark a blank as missing with NULLIF○Exercise: Mark a blank as missing with NULLIF○Choose a display fallback with COALESCE○Exercise: Choose a display fallback with COALESCE○Test decimal text with a regular expression○Exercise: Test decimal text with a regular expression○Choose a result value with CASE○Exercise: Choose a result value with CASE○Convert approved text to numeric○Exercise: Convert approved text to numeric✦Module Quiz
○Sum a measure at the chosen grain○Exercise: Sum a measure at the chosen grain○Calculate the mean of known observations○Exercise: Calculate the mean of known observations○Find the smallest known observation○Exercise: Find the smallest known observation○Find the largest known observation○Exercise: Find the largest known observation○Round a numeric report value○Exercise: Round a numeric report value✦Module Quiz
○Count matching rows with FILTER○Exercise: Count matching rows with FILTER○Define both sides of a rate○Exercise: Define both sides of a rate○Compare a row with a computed benchmark○Exercise: compare a row with a computed benchmark○Name analysis steps with CTEs○Exercise: name analysis steps with CTEs○Publish a query definition as a view○Exercise: Publish a query definition as a view○Commit a reporting change as one transaction○Exercise: Commit a reporting change as one transaction○Intake project 1: a reviewable clean layer○Intake project 2: region coverage○Intake project 3: one defensible coverage rate✦Module Quiz
○Make unmatched records visible○Exercise: make unmatched records visible○Prevent join fanout with preaggregation○Exercise: prevent join fanout with preaggregation○Use existence when you do not need child rows○Exercise: use existence when you do not need child rows○Refund project 1: one row per refunded order○Refund project 2: preserve the paid-order population○Refund project 3: reconcile the regional ledger✦Module Quiz
○Interpret an instant in a reporting zone○Exercise: Interpret an instant in a reporting zone○Keep adjacent time periods separate○Exercise: Keep adjacent time periods separate○Bucket calendar months without losing the year○Exercise: bucket calendar months without losing the year○Advance a calendar boundary with INTERVAL○Exercise: Advance a calendar boundary with INTERVAL○Read a date component with EXTRACT○Exercise: Read a date component with EXTRACT○Fill calendar gaps before measuring trends○Exercise: fill calendar gaps before measuring trends✦Module Quiz
○Keep detail rows while computing group shares○Exercise: keep detail rows while computing group shares○Assign a unique position with ROW_NUMBER○Exercise: Assign a unique position with ROW_NUMBER○Share tied positions with RANK○Exercise: Share tied positions with RANK○Number distinct value levels with DENSE_RANK○Exercise: Number distinct value levels with DENSE_RANK○Retain one source version per event○Exercise: Retain one source version per event✦Module Quiz
○Look back one observation with LAG○Exercise: Look back one observation with LAG○Look ahead one observation with LEAD○Exercise: Look ahead one observation with LEAD○Accumulate a running total with an explicit frame○Exercise: Accumulate a running total with an explicit frame○Restrict a total to a trailing row window○Exercise: Restrict a total to a trailing row window○Interpolate a percentile with PERCENTILE_CONT○Exercise: Interpolate a percentile with PERCENTILE_CONT○Choose an observed percentile with PERCENTILE_DISC○Exercise: Choose an observed percentile with PERCENTILE_DISC○Daily briefing 1: a complete daily layer○Daily briefing 2: cumulative and trailing totals○Daily briefing 3: changes with honest baselines○Rank a review queue without erasing ties○Exercise: rank a review queue without erasing ties✦Module Quiz
○Build a cohort from the first eligible purchase○Exercise: build a cohort from the first eligible purchase○Reduce repeated activity to one row per combination○Exercise: Reduce repeated activity to one row per combination○Count distinct known identities○Exercise: Count distinct known identities●Separate zero retention from an unobserved period○Exercise: separate zero retention from an unobserved period○Require the funnel steps to happen in sequence○Exercise: require the funnel steps to happen in sequence○Measure recency at a fixed cutoff○Exercise: Measure recency at a fixed cutoff○Measure purchase frequency at order grain○Exercise: Measure purchase frequency at order grain○State the monetary measure in a member report○Exercise: State the monetary measure in a member report○Apply a segment policy to prepared RFM measures○Exercise: Apply a segment policy to prepared RFM measures✦Module Quiz
○Create an empty reporting table○Exercise: Create an empty reporting table○Protect report row identity with a primary key○Exercise: Protect report row identity with a primary key○Protect a reporting relationship with REFERENCES○Exercise: Protect a reporting relationship with REFERENCES○Load query results with INSERT ... SELECT○Exercise: Load query results with INSERT ... SELECT○Model a report with facts and dimensions○Exercise: model a report with facts and dimensions○Reconcile independent sources and name the limits○Exercise: reconcile independent sources and name the limits○Inspect the proposed query plan○Exercise: Inspect the proposed query plan○Declare an index for a filter column○Exercise: Declare an index for a filter column✦Module Quiz
○Quarter review 1: freeze the report population○Quarter review 2: apply the refund cutoff once○Quarter review 3: regional evidence with an unmatched bucket○Quarter review 4: a monthly trend with a stable definition○Quarter review 5: publish a reconciled evidence table✦Module Quiz
○Define activity churn before counting players○Stage 1: establish the observed play stream○Stage 2: preserve each player and last-seen history○Stage 3: classify inactivity without losing exclusions○Stage 4: compare cohort and channel denominators○Stage 5: reconcile eligibility and boundary cases○Stage 6: prioritize investigation with honest evidence✦Module Quiz

Separate zero retention from an unobserved period

Data model

Example data

These objects are loaded at the start. Only the query inputs and their required lineage are listed; other tables in a shared seed are not part of this report.

cohort_readers

One row represents one prepared reader cohort assignment.

Field / SQL typeMeaningRules
reader · integerReader identity for the assignment; one assignment per reader in the sample, without a key constraint.Nullable; NULL means the identifier or reference is unrecorded.
cohort · dateFirst-of-month acquisition-cohort date, not the date of a later visit.Nullable; NULL means the calendar date is unrecorded.

No primary or unique key is declared; distinct sample identifiers are not a uniqueness guarantee.

The fixture has one assignment per reader, but the schema does not enforce that logical key. Cohort maturity depends on the fixed follow-up cutoff, not the fact that a row exists.

reading_visits

One row represents one recorded reading-group visit.

Field / SQL typeMeaningRules
reader · integerLogical reader identity matched to a cohort assignment.Nullable; NULL means the identifier or reference is unrecorded.
month · dateFirst-of-month activity date; reader-month pairs can repeat.Nullable; NULL means the calendar date is unrecorded.

No primary or unique key is declared; distinct sample identifiers are not a uniqueness guarantee.

No foreign key or unique reader-month constraint is declared. DISTINCT is needed before counting monthly retention.

Named intermediate results

These dictionaries describe the columns exposed by the named query steps. They are not extra preloaded tables or a complete answer query.

activity

One row represents one distinct reader activity month.

Field / SQL typeMeaningRules
reader · integerReader reference from reading_visits.May be NULL under its source or expression policy. Part of a logical composite identity/month key.
month · dateFirst-of-month activity date, not the acquisition cohort.May be NULL under its source or expression policy. Other part of the DISTINCT key; repeated visits or purchases in this month are collapsed.

This CTE is statement-local; it has no independently declared primary key, foreign key or NOT NULL constraint.

DISTINCT compares the full pair. It does not declare a physical unique key or prove the reference has a parent.

Relationship map

Aliases name query roles, not extra tables: c = cohort_readers, a = activity.

The identity equality is further limited to activity.month = (cohort + one calendar month). DISTINCT makes the activity identity/month pair unique. One cohort assignment has zero or one qualifying month-one match; one activity pair has zero or one assignment under the one-cohort-per-person contract. The cohort_readers physical schema does not enforce one assignment per reader, so duplicate assignments could multiply rows. This is a logical query match, not a declared foreign key between these inputs. Missing or unmatched references need not have a parent.

An inner join omits nonmatches. A left join retains its left population and a full join retains both populations, using NULLs only for the missing side. These outer-join NULLs differ from unknown values stored in a real row. A one-to-many detail match repeats the other side's fields; preaggregate before summing parent-level money. An EXISTS test only asks whether a match exists and does not copy all matching child rows.

A young cohort has not had the same chance to return as an older one. Compare only fully observed follow-up periods.

Month-one retention here means at least one paid purchase in the calendar month after acquisition. It does not mean within 30 days, nor any time on or after month one. The denominator remains the original purchaser cohort size. Use the distinct member-month result from the preceding practice so several purchases count as one retained member.

At the April 1, 2025 cutoff, January and February cohorts have complete next months; March does not. This lesson excludes immature cohorts from the month-one table rather than labeling them 0%. In a full retention grid, show their future cells as unobserved. A calendar month offset can be calculated as 12 * (activity_year - cohort_year) + activity_month - cohort_month, using EXTRACT; subtracting only month numbers would fail across years.

Read and run

A reading group follows a two-reader January cohort into February; one reader returns twice. In this separate demo, cohort_readers has one assignment per integer reader ID and a first-of-month cohort date. reading_visits has one visit record per row, with an integer reader ID and a first-of-month activity date; reader-month pairs may repeat. These are logical relationships, not declared constraints in the small demo.

The activity CTE makes reader-month pairs unique before the join. Matching cohort + INTERVAL '1 month' selects month one; requiring cohort + INTERVAL '2 months' <= cutoff ensures that entire next month has finished.

sql
WITH activity AS (
  SELECT DISTINCT reader, month FROM reading_visits
)
SELECT c.cohort::text AS cohort,
       COUNT(DISTINCT c.reader) AS cohort_size,
       COUNT(a.reader) AS retained
FROM cohort_readers c
LEFT JOIN activity a ON a.reader = c.reader
 AND a.month = (c.cohort + INTERVAL '1 month')::date
WHERE c.cohort + INTERVAL '2 months' <= DATE '2025-04-01'
GROUP BY c.cohort ORDER BY c.cohort;

The January denominator is two readers and the numerator is one reader, despite two visits. March is absent because its next month is not complete at the fixed cutoff.

A missing March row means its follow-up is incomplete, not that nobody returned. Keep that distinction in the report label.