Hello! Welcome to your next lesson in our "Advanced SQL for Business Analytics" module.
In our last session, you mastered funnel analysis, learning to track a user's journey through a sequence of events. We focused on short-term conversions, answering questions like "what percentage of users who clicked a notification went on to purchase?"
Today, we're shifting our perspective from a short sequence of events to long-term user behavior. We will tackle cohort analysis, one of the most powerful techniques for understanding customer loyalty and the lifetime value of users. This is a cornerstone of subscription businesses, e-commerce, and is highly relevant in your AdTech domain for measuring the long-term value of users acquired through different campaigns.
This lesson directly addresses the learning outcome: Prepare cohort data using SQL for retention analysis. By the end of this 60-minute session, you'll be able to write the SQL queries needed to transform raw transaction data into a structured format ready for retention analysis.
The "What" and "Why": A Business Analyst's View on Cohorts
Before we write a single line of SQL, we need to think like a Business Analyst. A cohort is simply a group of users who share a common characteristic. In retention analysis, that characteristic is typically the time they started using your product (e.g., all users who signed up in January 2023).
Cohort analysis helps us answer critical business questions:
- Are our newer users sticking around longer than our older users?
- Did a major product change in Q2 improve long-term user engagement?
- Which marketing channels bring in users with the highest long-term retention?
To properly set up our analysis, we need to make three key business decisions.
How to measure cohort retention
The article 'How to measure cohort retention' by Olga Berezovsky is an excellent guide to the business logic behind the analysis. We'll read a few sections to establish our framework.
Please read the sections 'Step 1. Define “active”', 'Step 2. Differentiate users from customers', and 'Step 3. Pick your retention type'. As you read, focus on these three foundational questions: Who are we tracking? (The cohort definition, e.g., users who made their first purchase). What counts as 'coming back'? (The definition of an 'active' event, e.g., any subsequent purchase). How do we measure time? (The retention type, e.g., are they active in a specific month or since that month).
For our exercise today, we will use a common e-commerce scenario:
- Cohort Definition: A user's cohort is defined by the month of their first purchase.
- Active Event: A user is considered "retained" in a given month if they make any purchase during that month.
- Timeline: We will track retention on a monthly basis.
The "How": A Step-by-Step SQL Workflow for Cohort Data
Now that we have our business logic, let's translate it into SQL. We will follow a detailed video tutorial that walks through the entire process. This process breaks down a complex problem into manageable steps, which is a great approach for any analysis.
The core steps are:
- Data Cleaning: Prepare the raw data by handling nulls and invalid records.
- Assign Cohort Month: For each customer, find the month of their very first purchase.
- Calculate Cohort Index: For each subsequent purchase, calculate how many months have passed since their first purchase. This "index" is the key to grouping user activity over time.
- Aggregate and Pivot: Count the number of unique customers for each cohort and each index to create the final, structured table.
Let's start the walkthrough.
Exploring Data in SQL and Tableau | Cohort Retention Analysis | Data Analyst Projects | SQL Projects
This video from Angelina Frimpong's channel provides a complete, practical walkthrough of creating a cohort analysis in SQL. We'll start with the initial data setup and cleaning.
Watch the video from the beginning to 12:33. The instructor will: Introduce the dataset and the goal. Import and inspect the data in SQL Server. Perform initial data cleaning, such as removing transactions with no CustomerID and those with negative quantity/price. Pay attention to how she uses a Common Table Expression (CTE) to build on the cleaned data.
Step 1: Assigning the Cohort Month
This is the first critical step in our logic. For every transaction in our dataset, we need to know which "cohort" the user belongs to. As we defined, the cohort is the month of the user's first purchase.
There are two common ways to achieve this in SQL:
- Using
GROUP BY: You can create a temporary table or CTE that groups byCustomerIDand finds theMIN(InvoiceDate). - Using Window Functions: You can use
MIN(InvoiceDate) OVER (PARTITION BY CustomerID). This is often more efficient as it avoids a separate join or subquery. This pattern should feel familiar from our last lesson on funnels!
Let's see how the video tackles this.
Exploring Data in SQL and Tableau | Cohort Retention Analysis | Data Analyst Projects | SQL Projects
Now, let's watch how to identify the first purchase date for each customer and establish the cohort.
Continue watching the video from 19:09 to 24:06. Focus on how a new temporary table (#cohort) is created by grouping all transactions by CustomerID and finding the MIN(InvoiceDate). The instructor also uses a date function to truncate this date to the first of the month, which is a best practice for standardizing cohort labels.
The key takeaway here is creating a lookup that maps every CustomerID to their CohortDate. For example: CustomerID 12345 -> 2010-12-01.
Step 2: Calculating the Cohort Index
This is the heart of the analysis. For every single transaction a customer makes, we want to ask: "How many months has it been since this customer's first purchase?" The answer is the Cohort Index.
- A
CohortIndexof 1 means the transaction happened in the same month as the first purchase. - A
CohortIndexof 2 means the transaction happened in the next month. - ...and so on.
To calculate this, we need to find the difference in months between the InvoiceDate of any given transaction and the CohortDate we found in the previous step.
The logic usually involves these calculations:
- Calculate the difference in years between
InvoiceDateandCohortDate. - Calculate the difference in months between
InvoiceDateandCohortDate. - Use a formula to combine these into a single index:
cohort_index = (year_difference * 12) + month_difference + 1
Let's see this in action.
Exploring Data in SQL and Tableau | Cohort Retention Analysis | Data Analyst Projects | SQL Projects
This is the most complex part of the query. Watch carefully how the instructor calculates the year and month differences and then combines them into the final cohort index.
Watch the video from 26:07 to 35:52. Don't worry about memorizing the exact syntax. Instead, focus on the logic: Joining the main transaction table with the #cohort table to have both the current InvoiceDate and the CohortDate in the same row. Extracting the year and month from both dates. Calculating year_diff and month_diff. Applying the final cohort_index formula.
After this step, you will have a dataset where every transaction is tagged with both the customer's cohort and a cohort index.

Test your understanding!
Imagine you have a table purchases with columns customer_id, purchase_date. A customer's cohort month is the month of their first purchase.
You are given the following intermediate table for a single customer C1:
| customer_id | purchase_date | cohort_month |
|---|---|---|
| C1 | 2023-01-15 | 2023-01-01 |
| C1 | 2023-01-20 | 2023-01-01 |
| C1 | 2023-03-10 | 2023-01-01 |
| C1 | 2024-02-05 | 2023-01-01 |
Using the formula cohort_index = (year_diff * 12) + month_diff + 1, what would the cohort_index be for the last purchase (2024-02-05)?
Show answer
Let's break it down:
purchase_date: 2024-02-05cohort_month: 2023-01-01
- Year Difference:
2024 - 2023 = 1 - Month Difference:
2 - 1 = 1 - Cohort Index Formula:
(1 * 12) + 1 + 1 = 14
The cohort_index would be 14. This means the purchase occurred in the 14th month of the customer's lifecycle (where the first month is month 1).
Step 3: Preparing the Final Cohort Table
Our final goal is to create a table that counts, for each cohort, how many unique customers were active in each subsequent month (i.e., for each cohort index).
The final output should look something like this (in a "long" format):
| cohort_month | cohort_index | customer_count |
|---|---|---|
| 2010-12-01 | 1 | 885 |
| 2010-12-01 | 2 | 324 |
| 2010-12-01 | 3 | 286 |
| ... | ... | ... |
| 2011-01-01 | 1 | 417 |
| 2011-01-01 | 2 | 92 |
| ... | ... | ... |
This format is perfect for data visualization tools like Tableau. To get here, we simply need to group our data by cohort_month and cohort_index and take a COUNT(DISTINCT customer_id).
Some analyses go one step further and PIVOT this table, but having it in the long format is often more flexible and completes our data preparation goal.
Exploring Data in SQL and Tableau | Cohort Retention Analysis | Data Analyst Projects | SQL Projects
Let's see how the prepared data is aggregated and pivoted to create the final analysis table.
Watch from 37:13 to 43:40. The instructor first gets the distinct customers for each cohort and index, and then uses the PIVOT operator to transform the data into a wide table. While the PIVOT syntax is specific to SQL Server, the logic of counting distinct customers per cohort/index group is universal.
Conclusion
Congratulations! You've just walked through the complete process of preparing data for cohort retention analysis. This is a challenging but incredibly valuable skill that combines data cleaning, date manipulation, window functions, and aggregation to produce powerful business insights.
Key Takeaways:
- Business First: Cohort analysis starts with clear business definitions for the cohort, the active event, and the timeline.
- Find the First Event: The first step in SQL is to identify each user's cohort by finding their first action (e.g.,
MIN(purchase_date)), often using aGROUP BYor aPARTITION BYwindow function. - The Cohort Index is Key: The
cohort_index, calculated as(year_diff * 12) + month_diff + 1, is the crucial metric that standardizes the user lifecycle across all cohorts. - Final Output: The prepared data is typically a table with
cohort_month,cohort_index, andcustomer_count, which is ready for calculating retention rates or for visualization.
Preview of the Next Lesson:
We have successfully prepared the data. In a future lesson in our "Business Analytics and Experimentation" module, we will learn how to "Calculate and interpret cohort retention rates to analyze user behavior over time." We will take the table you learned to build today, calculate the retention percentages, and use a tool like Tableau to create the classic color-coded cohort chart that is a staple of business reporting.