01 / 20

Cohort & Segmentation
Queries in SQL

Learn to slice your data into meaningful groups using GROUP BY and CASE expressions to answer real business questions.

SQL

What Is a Cohort?

A cohort is a group of users or records that share a common characteristic during a specific time frame. For example: all customers who signed up in January 2024, or all students who enrolled in Fall semester.

What Is Segmentation?

Segmentation divides data into categories based on attributes or calculated conditions. Instead of grouping by time alone, you create custom buckets: high-value vs. low-value customers, or age groups like teen, adult, senior.

Cohort
Groups share a time-based event: sign-up month, purchase quarter
Segment
Groups share an attribute-based condition: spend tier, region, behavior

Why Cohort & Segmentation Matter

Raw Data GROUP BY + CASE Cohort A Jan sign-ups Segment B High spenders Segment C Low spenders

Core Pattern: GROUP BY

SELECT   column_to_group,
         AGG_FUNC(measure) AS result
FROM     table_name
GROUP BY column_to_group;

Core Pattern: CASE Expression

CASE
  WHEN condition_1 THEN 'Label A'
  WHEN condition_2 THEN 'Label B'
  ELSE 'Label C'
END AS segment

GROUP BY vs. CASE

GROUP BY CASE
Purpose Split rows by existing column values Create new labels from conditions
Placement Its own clause after WHERE Inside SELECT (or GROUP BY)
Used alone? Yes: groups by raw column Yes: adds a column, no grouping
Combined? GROUP BY + CASE = custom cohorts

How to Build a Segmentation Query

1
Identify the question: What groups do you want to compare? (e.g., spending tiers, sign-up months)
2
Write the CASE expression: Define conditions and labels for each segment or cohort.
3
Choose your aggregate: Pick COUNT, SUM, AVG, etc. to measure each group.
4
GROUP BY the CASE alias (or repeat the expression). Add ORDER BY for clarity.
5
Filter if needed: Use HAVING to remove groups below a threshold.

Example 1: Monthly Sign-Up Cohorts

Count how many users signed up each month.

SELECT
  DATE_TRUNC('month', signup_date) AS cohort_month,
  COUNT(*)                            AS user_count
FROM users
GROUP BY cohort_month
ORDER BY cohort_month;

Example 2: Spending Tier Segments

Classify customers into spending tiers and count each.

SELECT
  CASE
    WHEN total_spent >= 500 THEN 'High'
    WHEN total_spent >= 100 THEN 'Medium'
    ELSE 'Low'
  END            AS spend_tier,
  COUNT(*)      AS customer_count,
  AVG(total_spent) AS avg_spend
FROM customers
GROUP BY spend_tier;

Example 3: Cohort + Segment Combined

For each sign-up month, count how many users fall into each age group.

SELECT
  DATE_TRUNC('month', signup_date) AS cohort,
  CASE
    WHEN age < 18  THEN 'Teen'
    WHEN age < 30  THEN 'Young Adult'
    WHEN age < 60  THEN 'Adult'
    ELSE 'Senior'
  END                                  AS age_group,
  COUNT(*)                              AS users
FROM users
GROUP BY cohort, age_group
ORDER BY cohort, age_group;

How the Query Flows

Step 1 FROM table Step 2 GROUP BY Step 3 SELECT / CASE Result Table segment count avg_val High 142 724.50 Medium 389 248.10 Low 1,204 42.30

Filtering Groups with HAVING

WHERE filters individual rows before grouping. HAVING filters entire groups after aggregation. Use HAVING to keep only segments that meet a minimum threshold.

SELECT
  CASE
    WHEN grade >= 90 THEN 'A'
    WHEN grade >= 80 THEN 'B'
    WHEN grade >= 70 THEN 'C'
    ELSE 'Below C'
  END            AS letter_grade,
  COUNT(*)      AS students
FROM scores
GROUP BY letter_grade
HAVING COUNT(*) >= 5;

Common Mistakes to Avoid

✕ Non-aggregated column in SELECT
Every column in SELECT must be either in the GROUP BY clause or wrapped in an aggregate function. Otherwise, the database doesn't know which value to show.
✕ Using WHERE instead of HAVING
WHERE cannot reference aggregates like COUNT or AVG. Use HAVING to filter after grouping. WHERE = row filter; HAVING = group filter.
✕ Missing ELSE in CASE
Without ELSE, unmatched rows get NULL. This creates a mystery segment. Always include ELSE with a clear fallback label like 'Other'.

Summary of Key Clauses

Clause When It Runs What It Does
CASE Per row, during SELECT Creates custom labels/segments
GROUP BY After WHERE Collapses rows into groups
AGG functions During GROUP BY COUNT, SUM, AVG, MAX, MIN
HAVING After GROUP BY Filters groups by aggregate condition
ORDER BY Last Sorts the final output

Question 1 of 5

Which SQL clause collapses rows that share the same value into a single output row?

Question 2 of 5

What happens if you omit the ELSE clause in a CASE expression?

Question 3 of 5

What does the HAVING clause do in this query?

Question 4 of 5

You want to count orders per month. Which function rounds a date down to the first of its month?

Question 5 of 5

This query will produce an error. Which column causes the problem?