← All articlesData Science

Cohort Retention and Funnel Analysis in SQL: A Step-by-Step Project with Real Output

By Skillancy Editorial Team · 2 December 2026 · 41 min read

Reviewed by Rishav Kumar, Principal Data Analyst, Walmart Global Tech

Skillancy cover: Cohort Retention and Funnel Analysis in SQL, a Meesho-style project step by step. The January cohort keeps 41.6%, 37.2% and 31.9% in months 0 to 2, the April sale cohort 47.3%, 32.2% and 24.2%. The same funnel counted unordered shows 19.5% conversion, but 11.3% when steps must happen in order

Cohort retention analysis groups users by when they started, usually their signup month, and tracks what share of each group comes back in every month after. Funnel analysis counts how many users get through each step of a journey, such as product view → add to cart → checkout → order, and where they drop off. Together they answer the two questions every Indian consumer app asks each week: are the users we acquire sticking around? and where are we losing buyers? This guide builds both in SQL, step by step, as a Meesho-style project on 7,200 users and 10,506 orders. Every query runs in PostgreSQL, and every number comes from running it. Along the way it shows four mistakes that quietly fake retention numbers. One of them made a funnel report 19.5% conversion when the strict step-by-step rate was 11.3%.

QuestionShort answer
What is a cohort in data analysis?A group of users who share a starting event in the same period, such as signing up in January 2026
What does retention rate mean?Active users in period N ÷ users in the cohort at the start. Month 0 is the signup month
Which SQL concepts does cohort analysis use?CTEs, DATE_TRUNC, date differences, COUNT(DISTINCT), joins and a pivot (FILTER or CASE WHEN)
How is a funnel query different from counting events?A funnel checks the order and timing of steps per user. Plain counts don't, so they overstate conversion
What are the most common mistakes?Counting orders instead of users, dividing by the wrong base, showing half-finished months, and mixing retention definitions
Can I run this without installing anything?Yes. Paste the dataset script into the free Skillancy SQL compiler, which runs PostgreSQL in your browser
Data note: the users, orders and events in this post are simulated by the SQL script below, with a fixed random seed, so you get the same rows we did. They're modelled on a social-commerce app like Meesho, with Tier 1, 2 and 3 cities and a big April sale, but they aren't any company's real data. The queries are the ones you'd run on real event tables.

New to the SQL pieces? The free SQL lessons on CTEs, date functions, GROUP BY, window functions and pivoting rows into columns cover the building blocks, each with a practice question.

What is cohort analysis?

A cohort is a group of people who share a starting point in the same period: everyone who signed up in January, everyone who placed their first order during Diwali week, everyone who installed the app from an Instagram campaign. Cohort analysis follows each group over time and compares the groups with each other.

It exists because overall numbers hide what's happening. Say monthly active buyers grow from 2,000 to 2,600. That looks healthy, but it could be a big burst of new signups covering for old users leaving. A cohort table separates the two: each row is one group of users, each column is how long they've been around, so you can see whether users who joined in June behave better or worse than users who joined in January at the same age.

Type of cohortGrouped byExample question
Acquisition cohortWhen users started (signup, first order, install)Do March signups return as often as January signups?
Behavioural cohortWhat users did (used a coupon, bought in two categories, used COD)Do users who order in 2+ categories retain better?
Source cohortWhere users came from (sale, referral, ads, organic)Are sale-week signups worth what we paid for them?

This guide uses monthly acquisition cohorts and then splits one of them by source.

Four ways to define retention

"Retention" sounds like one number, but teams define it in different ways. Pick one, write it down, and keep it the same on every dashboard.

DefinitionA user counts as retained in period N if…Typical use
N-month (classic) retentionThey were active in calendar month N after their cohort monthMonthly cohort tables, like the one we build
N-day window retentionThey were active between day 30N and 30N+29 after their own start dateMobile apps, when signup day varies a lot
Unbounded ("on or after") retentionThey were active in period N or any later periodSubscription and SaaS, smoother curves
Repeat-purchase rateThey placed a second order within X days of their firstE-commerce and quick commerce

Product analytics tools use the same ideas under different names. Amplitude, for example, calls its two main methods "Return On" (N-day) and "Return On or After" (unbounded).

What is funnel analysis?

A funnel is an ordered series of steps a user must go through to reach a goal. Funnel analysis counts how many users reach each step and works out two rates:

  • Step conversion = users at this step ÷ users at the previous step. It shows where people drop off.
  • Overall conversion = users at this step ÷ users at the first step. It shows how much of the original traffic you keep.

A real funnel has two rules that plain counting ignores. Steps must happen in order (a checkout only counts if it came after the cart add), and they must happen within a time window (a checkout three weeks later is a different shopping session). Tools like Mixpanel use the same two settings, which they call the order of steps and the conversion window. We'll write both in SQL.

The project: a Meesho-style retention and checkout question

Here is the brief, written the way a product manager would send it:

"We acquired a lot of users in the 1–10 April sale. Are they sticking around like our regular signups? Also, conversion in the July sale week looked fine on the dashboard, but orders feel low. Where are we losing people in checkout, and is it worse in smaller cities?"

That's three analyses: a cohort retention table, a cohort split by signup source, and an ordered checkout funnel by city tier. They're the same analyses you build in the graded Product Funnel & Cohort Retention project in week 2 of Data Science with AI.

The dataset

Three tables, one row per user, one row per order and one row per app event:

TableRowsColumns
users7,200user_id, signup_date (Jan–Jun 2026), city_tier (Tier 1/2/3), signup_source (organic or sale)
purchases10,506purchase_id, user_id, order_date, amount (₹)
events9,139user_id, event (product_view, add_to_cart, checkout, order), event_time (1–7 July 2026)

The data was pulled on 15 July 2026, halfway through the month. Keep that date in mind: it causes Mistake 3.

Paste this script into the SQL compiler and run it once. It creates the three tables (the compiler's own sample tables are left alone), and every query after it runs on the same rows.

-- Synthetic Meesho-style e-commerce data for the cohort retention + funnel post.
-- PostgreSQL. Same seed = same rows. Snapshot date: 2026-07-15.
SELECT setseed(0.42);

CREATE TABLE users AS
WITH base AS (
  SELECT g AS user_id,
         DATE '2026-01-01' + (random()*180)::int AS signup_date
  FROM generate_series(1, 6000) g
  UNION ALL                                   -- extra signups during a big 1-10 April sale
  SELECT 6000 + g, DATE '2026-04-01' + (random()*9)::int
  FROM generate_series(1, 1200) g
)
SELECT user_id, signup_date,
       (ARRAY['Tier 1','Tier 2','Tier 3'])[1 + floor(random()*3)::int] AS city_tier,
       CASE WHEN user_id > 6000 THEN 'sale' ELSE 'organic' END AS signup_source
FROM base;

-- One row per user x 30-day period x order slot, with its random draws stored first
CREATE TABLE grid AS
SELECT u.user_id, u.signup_date, u.signup_source, k, n,
       random() AS p, random() AS d, random() AS a
FROM users u, generate_series(0, 7) k, generate_series(1, 3) n;

CREATE TABLE purchases AS
SELECT row_number() OVER (ORDER BY user_id, k, n)::int AS purchase_id,
       user_id,
       signup_date + (k*30 + CASE WHEN k = 0 THEN floor(d*d*30) ELSE floor(d*30) END::int) AS order_date,   -- first orders cluster in the first days
       (149 + floor(a*850))::int AS amount
FROM grid
WHERE p < (CASE WHEN k = 0 THEN 0.42 ELSE 0.24 * power(0.82, k - 1) END)   -- decays with time
        * (CASE WHEN n = 1 THEN 1.0 ELSE 0.35 END)                        -- repeat orders rarer
        * (CASE WHEN signup_source = 'sale' AND k > 0 THEN 0.6 ELSE 1.0 END);   -- sale users return less
DELETE FROM purchases WHERE order_date > DATE '2026-07-15';
DROP TABLE grid;

-- Event log for a 1-7 July sale week: product_view -> add_to_cart -> checkout -> order.
-- About 1 in 8 shoppers use "Buy Now", which skips the cart.
CREATE TABLE events AS
WITH s AS MATERIALIZED (
  SELECT u.user_id, u.city_tier,
         TIMESTAMP '2026-07-01' + random() * INTERVAL '6 days' AS t0,
         random() AS r1, random() AS r2, random() AS r3, random() AS bn, random() AS pick
  FROM users u
), shoppers AS (SELECT * FROM s WHERE pick < 0.7)
SELECT user_id, 'product_view' AS event, t0 AS event_time FROM shoppers
UNION ALL
SELECT user_id, 'add_to_cart', t0 + INTERVAL '4 minutes' FROM shoppers
 WHERE bn >= 0.12 AND r1 < CASE city_tier WHEN 'Tier 1' THEN 0.36 WHEN 'Tier 2' THEN 0.33 ELSE 0.30 END
UNION ALL
SELECT user_id, 'checkout', t0 + INTERVAL '15 minutes' FROM shoppers
 WHERE (bn >= 0.12 AND r1 < CASE city_tier WHEN 'Tier 1' THEN 0.36 WHEN 'Tier 2' THEN 0.33 ELSE 0.30 END AND r2 < 0.55)
    OR bn < 0.12
UNION ALL
SELECT user_id, 'order', t0 + INTERVAL '19 minutes' FROM shoppers
 WHERE ((bn >= 0.12 AND r1 < CASE city_tier WHEN 'Tier 1' THEN 0.36 WHEN 'Tier 2' THEN 0.33 ELSE 0.30 END AND r2 < 0.55)
        OR bn < 0.12)
   AND r3 < CASE city_tier WHEN 'Tier 3' THEN 0.58 ELSE 0.72 END
UNION ALL   -- wishlist items synced into the cart days before the session
SELECT user_id, 'add_to_cart', t0 - INTERVAL '2 days' FROM shoppers WHERE bn < 0.12 AND r3 < 0.3
UNION ALL   -- a checkout that happens two days later (outside a 1-day window)
SELECT user_id, 'checkout', t0 + INTERVAL '2 days' FROM shoppers
 WHERE bn >= 0.12 AND r1 < 0.30 AND r2 >= 0.55 AND r2 < 0.62;

A quick check that you have the same data:

SELECT (SELECT COUNT(*) FROM users) AS users,
       (SELECT COUNT(*) FROM purchases) AS orders,
       (SELECT COUNT(DISTINCT user_id) FROM purchases) AS buyers,
       (SELECT COUNT(*) FROM events) AS events,
       (SELECT MIN(order_date) FROM purchases) AS first_order,
       (SELECT MAX(order_date) FROM purchases) AS last_order
usersordersbuyerseventsfirst_orderlast_order
720010506567691392026-01-012026-07-15

Each user has a signup date, a city tier and a source. User 6001 is one of the 1,200 extra users who signed up during the April sale:

user_idsignup_datecity_tiersignup_source
12026-05-15Tier 2organic
22026-06-19Tier 1organic
32026-01-18Tier 1organic
60012026-04-07Tier 2sale

Cohort retention in SQL, step by step

Step 1: put every user in a cohort

The cohort is the month of the signup date. DATE_TRUNC('month', signup_date) turns 18 January 2026 into 1 January 2026, so every January signup gets the same label.

SELECT DATE_TRUNC('month', signup_date)::date AS cohort_month,
       COUNT(*) AS cohort_users
FROM users
GROUP BY 1
ORDER BY 1
cohort_monthcohort_users
2026-01-01990
2026-02-01977
2026-03-01995
2026-04-012190
2026-05-011038
2026-06-011010

The cohorts are similar in size, about 1,000 users each, except April, which has 2,190 because of the sale. That size difference is why we'll work in percentages of each cohort, not raw counts.

Step 2: work out the month number of each order

Now each order needs a month number: how many calendar months after the cohort month it happened. An order in the signup month is month 0, the next calendar month is month 1, and so on. Here are the orders of one January user:

WITH cohorts AS (
  SELECT user_id, DATE_TRUNC('month', signup_date)::date AS cohort_month
  FROM users
)
SELECT p.user_id, c.cohort_month, p.order_date,
       DATE_TRUNC('month', p.order_date)::date AS order_month,
       (EXTRACT(YEAR  FROM AGE(DATE_TRUNC('month', p.order_date), c.cohort_month)) * 12
      + EXTRACT(MONTH FROM AGE(DATE_TRUNC('month', p.order_date), c.cohort_month)))::int AS month_number
FROM purchases p
JOIN cohorts c USING (user_id)
WHERE p.user_id = 112
ORDER BY p.order_date
user_idcohort_monthorder_dateorder_monthmonth_number
1122026-01-012026-01-242026-01-010
1122026-01-012026-01-312026-01-010
1122026-01-012026-05-182026-05-014
1122026-01-012026-06-292026-06-015

PostgreSQL has no one-word "months between" function, so we use AGE() on the two month starts and turn years and months into a single number. Other databases have a direct function (see the syntax table near the end). This user ordered twice in January (month 0), went quiet, and came back in May (month 4) and June (month 5). In a retention table they count once in month 0, once in month 4 and once in month 5. Two orders in one month still make one active user.

Step 3: count active users and divide by the cohort size

This is the core query. We save it as a view called cohort_retention so the later steps can reuse it:

CREATE VIEW cohort_retention AS
WITH cohorts AS (
  SELECT user_id, DATE_TRUNC('month', signup_date)::date AS cohort_month
  FROM users
),
cohort_size AS (
  SELECT cohort_month, COUNT(*) AS cohort_users
  FROM cohorts
  GROUP BY cohort_month
),
activity AS (
  SELECT DISTINCT
         c.cohort_month,
         p.user_id,
         (EXTRACT(YEAR  FROM AGE(DATE_TRUNC('month', p.order_date), c.cohort_month)) * 12
        + EXTRACT(MONTH FROM AGE(DATE_TRUNC('month', p.order_date), c.cohort_month)))::int AS month_number
  FROM purchases p
  JOIN cohorts c USING (user_id)
)
SELECT a.cohort_month,
       s.cohort_users,
       a.month_number,
       COUNT(*) AS active_users,
       ROUND(100.0 * COUNT(*) / s.cohort_users, 1) AS retention_pct
FROM activity a
JOIN cohort_size s USING (cohort_month)
GROUP BY a.cohort_month, s.cohort_users, a.month_number;

Three details matter here, and each one is a mistake if you get it wrong:

1. SELECT DISTINCT in activity keeps one row per user per month, however many orders they placed.

2. cohort_size counts everyone who signed up, from users, not only people who ordered.

3. The join to cohort_size gives every row the same base, so retention_pct is "% of the cohort".

Here's the January cohort in long format, one row per month number:

SELECT *
FROM cohort_retention
WHERE cohort_month = DATE '2026-01-01'
ORDER BY month_number
cohort_monthcohort_usersmonth_numberactive_usersretention_pct
2026-01-01990041241.6
2026-01-01990136837.2
2026-01-01990231631.9
2026-01-01990326426.7
2026-01-01990422122.3
2026-01-01990517017.2
2026-01-019906787.9

Read it as: of the 990 users who signed up in January, 412 (41.6%) ordered in January, 368 (37.2%) ordered in February, and so on. The July value (month 6) is only 7.9%. Hold that thought.

Step 4: pivot it into a retention table

A retention table has one row per cohort and one column per month number. In PostgreSQL, MAX(...) FILTER (WHERE month_number = N) turns rows into columns. The WHERE line leaves out July, because the data stops on 15 July and July isn't finished yet:

WITH r AS (
  SELECT *,
         (cohort_month + MAKE_INTERVAL(months => month_number))::date AS calendar_month
  FROM cohort_retention
)
SELECT cohort_month, cohort_users,
       MAX(retention_pct) FILTER (WHERE month_number = 0) AS m0,
       MAX(retention_pct) FILTER (WHERE month_number = 1) AS m1,
       MAX(retention_pct) FILTER (WHERE month_number = 2) AS m2,
       MAX(retention_pct) FILTER (WHERE month_number = 3) AS m3,
       MAX(retention_pct) FILTER (WHERE month_number = 4) AS m4,
       MAX(retention_pct) FILTER (WHERE month_number = 5) AS m5
FROM r
WHERE calendar_month < DATE '2026-07-01'   -- drop the half-finished month (snapshot: 15 Jul)
GROUP BY cohort_month, cohort_users
ORDER BY cohort_month
cohort_monthcohort_usersm0m1m2m3m4m5
2026-01-0199041.637.231.926.722.317.2
2026-02-0197743.536.833.028.420.6NULL
2026-03-0199541.137.430.927.8NULLNULL
2026-04-01219047.332.224.2NULLNULLNULL
2026-05-01103842.240.8NULLNULLNULLNULL
2026-06-01101042.1NULLNULLNULLNULLNULL

NULL here means "not observed yet", not zero: the June cohort can't have a month-1 value until July is over. Coloured in, the same table is the retention heatmap you see in every product review:

Cohort retention heatmap from PostgreSQL. Rows are monthly signup cohorts from January to June 2026, columns are months since signup. January keeps 41.6% in month 0, 37.2% in month 1, 31.9% in month 2, 26.7% in month 3, 22.3% in month 4 and 17.2% in month 5. The April sale cohort has 2,190 users and the best month 0 at 47.3%, but drops to 32.2% in month 1 and 24.2% in month 2.

How to read a cohort retention table

Read it…What it tells youIn our table
Across a rowHow one cohort decays over its lifeJanuary falls from 41.6% to 17.2% over five months
Down a columnWhether newer cohorts are better or worse at the same ageMonth 1 is steady at 36.8–40.8%, except April at 32.2%
Along a diagonalOne calendar month across all cohorts (a sale, an outage, a price change)Every cell on the July diagonal is low. See Mistake 3
Where the curve flattensYour loyal core, the users you'll likely keepNot flat yet by month 5. Check again with more months

The one cohort that stands out is April. It's the biggest and has the best month 0 (47.3%), but the weakest month 1 and month 2. We'll dig into why after the mistakes.

Four mistakes that fake your retention numbers

Each mistake below runs on the same data as the correct table, so you can see exactly how far off it is.

Mistake 1: counting orders instead of users

COUNT(*) on orders counts a user who ordered three times as three. Retention is about people, so you need COUNT(DISTINCT user_id):

WITH jan AS (
  SELECT user_id FROM users
  WHERE DATE_TRUNC('month', signup_date) = DATE '2026-01-01'
)
SELECT (EXTRACT(MONTH FROM AGE(DATE_TRUNC('month', p.order_date), DATE '2026-01-01')))::int AS month_number,
       COUNT(*)                  AS orders,
       COUNT(DISTINCT p.user_id) AS buyers,
       ROUND(100.0 * COUNT(*)                  / (SELECT COUNT(*) FROM jan), 1) AS wrong_pct,
       ROUND(100.0 * COUNT(DISTINCT p.user_id) / (SELECT COUNT(*) FROM jan), 1) AS right_pct
FROM purchases p
JOIN jan USING (user_id)
GROUP BY 1
ORDER BY 1
month_numberordersbuyerswrong_pctright_pct
048141248.641.6
141536841.937.2
237331637.731.9
329326429.626.7
424122124.322.3
518617018.817.2
680788.17.9

Every month is inflated, and the error is biggest in month 0 (48.6% instead of 41.6%), where repeat orders are most common. On a cohort with heavy repeat buyers, COUNT(*) can even push "retention" above 100%.

Mistake 2: dividing by buyers instead of everyone who signed up

Many tutorials divide each month by the month-0 count. That only works if month 0 is "everyone in the cohort". When the cohort is signups and month 0 is people who ordered, the base silently changes from 990 users to 412:

SELECT month_number,
       active_users,
       retention_pct AS pct_of_signups,
       ROUND(100.0 * active_users
             / FIRST_VALUE(active_users) OVER (ORDER BY month_number), 1) AS pct_of_month0_buyers
FROM cohort_retention
WHERE cohort_month = DATE '2026-01-01'
ORDER BY month_number
month_numberactive_userspct_of_signupspct_of_month0_buyers
041241.6100.0
136837.289.3
231631.976.7
326426.764.1
422122.353.6
517017.241.3
6787.918.9

Month-1 "retention" jumps from 37.2% to 89.3%. Neither number is wrong in itself, but they answer different questions. The first is "what share of signups order in month 1". The second is "what share of first-month buyers order again". Label which one you're showing. Mixing the two on one dashboard is a classic way to make a product look 2.4 times healthier than it is.

Mistake 3: showing half-finished months as real drops

Here's the same table without the WHERE calendar_month < '2026-07-01' line:

SELECT cohort_month, cohort_users,
       MAX(retention_pct) FILTER (WHERE month_number = 0) AS m0,
       MAX(retention_pct) FILTER (WHERE month_number = 1) AS m1,
       MAX(retention_pct) FILTER (WHERE month_number = 2) AS m2,
       MAX(retention_pct) FILTER (WHERE month_number = 3) AS m3,
       MAX(retention_pct) FILTER (WHERE month_number = 4) AS m4,
       MAX(retention_pct) FILTER (WHERE month_number = 5) AS m5,
       MAX(retention_pct) FILTER (WHERE month_number = 6) AS m6
FROM cohort_retention
GROUP BY cohort_month, cohort_users
ORDER BY cohort_month
cohort_monthcohort_usersm0m1m2m3m4m5m6
2026-01-0199041.637.231.926.722.317.27.9
2026-02-0197743.536.833.028.420.69.7NULL
2026-03-0199541.137.430.927.812.9NULLNULL
2026-04-01219047.332.224.210.8NULLNULLNULL
2026-05-01103842.240.816.1NULLNULLNULLNULL
2026-06-01101042.119.9NULLNULLNULLNULLNULL

Look at the last filled cell in every row: 7.9, 9.7, 12.9, 10.8, 16.1, 19.9. They form a diagonal, and every one of them is July, a month with only 15 days of data. This query puts each July value next to the average for the same month number in complete months:

WITH r AS (
  SELECT *, (cohort_month + MAKE_INTERVAL(months => month_number))::date AS calendar_month
  FROM cohort_retention
),
typical AS (                     -- average for the same month number, complete months only
  SELECT month_number, ROUND(AVG(retention_pct), 1) AS avg_complete
  FROM r
  WHERE calendar_month < DATE '2026-07-01'
  GROUP BY month_number
)
SELECT r.cohort_month, r.month_number, r.calendar_month,
       r.retention_pct AS july_value,
       t.avg_complete  AS same_month_number_in_complete_months
FROM r
LEFT JOIN typical t USING (month_number)
WHERE r.calendar_month = DATE '2026-07-01'
ORDER BY r.cohort_month
cohort_monthmonth_numbercalendar_monthjuly_valuesame_month_number_in_complete_months
2026-01-0162026-07-017.9NULL
2026-02-0152026-07-019.717.2
2026-03-0142026-07-0112.921.5
2026-04-0132026-07-0110.827.6
2026-05-0122026-07-0116.130.0
2026-06-0112026-07-0119.936.9

Every July value is only 40–60% of normal. That isn't users leaving. It's half a month of orders. Someone looking at this table on 15 July would report a "sharp drop in retention across all cohorts" that doesn't exist. The fix: leave out, grey out or label any period that hasn't finished. Product analytics tools handle the same problem by leaving users who haven't reached a period out of that period's base.

Mistake 4: mixing calendar months with days since signup

"Month 1" can mean the next calendar month or days 30–59 after signup. They aren't the same: a user who signs up on 28 January and orders on 3 February is in calendar month 1 after only 6 days. Here are both definitions on the same users (only cohorts where both windows are complete):

WITH u AS (
  SELECT user_id, signup_date, DATE_TRUNC('month', signup_date)::date AS cohort_month
  FROM users
  WHERE signup_date <= DATE '2026-04-30'   -- day 59 and the next calendar month are both complete
),
flags AS (
  SELECT u.cohort_month, u.user_id,
         BOOL_OR(DATE_TRUNC('month', p.order_date) = u.cohort_month + INTERVAL '1 month') AS calendar_m1,
         BOOL_OR(p.order_date - u.signup_date BETWEEN 30 AND 59)                      AS days_30_59
  FROM u LEFT JOIN purchases p USING (user_id)
  GROUP BY u.cohort_month, u.user_id
)
SELECT cohort_month,
       COUNT(*) AS cohort_users,
       ROUND(100.0 * COUNT(*) FILTER (WHERE calendar_m1) / COUNT(*), 1) AS calendar_month_1_pct,
       ROUND(100.0 * COUNT(*) FILTER (WHERE days_30_59)  / COUNT(*), 1) AS days_30_59_pct
FROM flags
WHERE cohort_month <= DATE '2026-04-01'
GROUP BY cohort_month
ORDER BY cohort_month
cohort_monthcohort_userscalendar_month_1_pctdays_30_59_pct
2026-01-0199037.236.0
2026-02-0197736.834.3
2026-03-0199537.435.7
2026-04-01219032.229.9

In our data the two are close, 1.2 to 2.5 points apart, but they're not interchangeable. The gap grows when signups bunch up at the end of a month (say, a sale on the 25th). Calendar months are easy to explain and match monthly reporting. Day windows treat every user equally. Choose one per report, and say which in the chart title.

What the cohorts tell us

Sale cohorts: bigger, but they don't stay

The April cohort mixes 990 organic signups with 1,200 users who joined during the 1–10 April sale. Splitting it by signup_source answers the product manager's first question:

WITH april AS (
  SELECT user_id, signup_source
  FROM users
  WHERE DATE_TRUNC('month', signup_date) = DATE '2026-04-01'
),
sizes AS (
  SELECT signup_source, COUNT(*) AS users FROM april GROUP BY signup_source
),
activity AS (
  SELECT DISTINCT a.signup_source, p.user_id,
         EXTRACT(MONTH FROM AGE(DATE_TRUNC('month', p.order_date), DATE '2026-04-01'))::int AS month_number
  FROM purchases p
  JOIN april a USING (user_id)
)
SELECT s.signup_source, s.users,
       ROUND(100.0 * COUNT(*) FILTER (WHERE month_number = 0) / s.users, 1) AS m0,
       ROUND(100.0 * COUNT(*) FILTER (WHERE month_number = 1) / s.users, 1) AS m1,
       ROUND(100.0 * COUNT(*) FILTER (WHERE month_number = 2) / s.users, 1) AS m2
FROM activity a
JOIN sizes s USING (signup_source)
GROUP BY s.signup_source, s.users
ORDER BY s.signup_source DESC
signup_sourceusersm0m1m2
sale120052.725.617.9
organic99040.840.231.9

Sale signups were more likely to order straight away (52.7% in April vs 40.8%), which is what sale prices are for. But by June only 17.9% were still ordering, against 31.9% of organic users who joined the same month. The headline for the PM: the sale bought a lot of first orders, but each sale user is worth far less over time, so judge future sales on month-2 retention, not on signups. A blended April number (32.2% in month 1) hides both stories.

Repeat purchase within 30 days

E-commerce teams often track a simpler number: of first-time buyers, how many order again within 30 days? It doesn't depend on calendar months at all:

WITH first_order AS (
  SELECT user_id, MIN(order_date) AS first_order_date
  FROM purchases
  GROUP BY user_id
),
repeaters AS (
  SELECT f.user_id,
         EXISTS (
           SELECT 1 FROM purchases p
           WHERE p.user_id = f.user_id
             AND p.order_date >  f.first_order_date
             AND p.order_date <= f.first_order_date + 30
         ) AS repeated_30d
  FROM first_order f
  WHERE f.first_order_date <= DATE '2026-07-15' - 30   -- give everyone a full 30 days
)
SELECT DATE_TRUNC('month', u.signup_date)::date AS cohort_month,
       COUNT(*) AS first_time_buyers,
       ROUND(100.0 * COUNT(*) FILTER (WHERE repeated_30d) / COUNT(*), 1) AS repeat_30d_pct
FROM repeaters r
JOIN users u USING (user_id)
WHERE u.signup_date < DATE '2026-06-01'   -- June signups have not had time to repeat
GROUP BY 1
ORDER BY 1
cohort_monthfirst_time_buyersrepeat_30d_pct
2026-01-0188827.6
2026-02-0185628.5
2026-03-0179630.8
2026-04-01156427.0
2026-05-0161830.7

The WHERE line keeps only buyers whose first order is at least 30 days before the snapshot, so everyone has had a full 30 days to come back. That's Mistake 3's fix applied to a different metric. June signups are left out for the same reason. About 27–31% of first-time buyers come back within a month, and April is again the lowest.

Funnel analysis in SQL

Now the second question: where is checkout losing people in the July sale week?

The naive funnel: count users with each event

The quickest funnel counts distinct users per event:

SELECT event,
       COUNT(DISTINCT user_id) AS users
FROM events
GROUP BY event
ORDER BY ARRAY_POSITION(ARRAY['product_view', 'add_to_cart', 'checkout', 'order'], event)
eventusers
product_view5006
add_to_cart1659
checkout1500
order974

That gives 974 ÷ 5,006 = 19.5% of viewers ordering. It looks fine, and it's what most dashboards show. But this query never checks that a user who ordered also viewed and added to cart first, or that the steps happened in the same session.

The strict funnel: each step after the previous one, within a day

To build a real funnel, take each user's first product view, then the first cart add after it, then the first checkout after that, and so on, all within 1 day of the view. A LEFT JOIN keeps users who stop at a step, with NULL for the steps they never reached:

CREATE VIEW strict_funnel_users AS
WITH views AS (                                 -- step 1: first product view
  SELECT user_id, MIN(event_time) AS viewed_at
  FROM events
  WHERE event = 'product_view'
  GROUP BY user_id
),
carts AS (                                      -- step 2: first cart add after the view
  SELECT v.user_id, v.viewed_at, MIN(e.event_time) AS carted_at
  FROM views v
  LEFT JOIN events e
         ON e.user_id = v.user_id AND e.event = 'add_to_cart'
        AND e.event_time >  v.viewed_at
        AND e.event_time <= v.viewed_at + INTERVAL '1 day'
  GROUP BY v.user_id, v.viewed_at
),
checkouts AS (                                  -- step 3: first checkout after the cart add
  SELECT c.*, MIN(e.event_time) AS checked_out_at
  FROM carts c
  LEFT JOIN events e
         ON e.user_id = c.user_id AND e.event = 'checkout'
        AND e.event_time >  c.carted_at
        AND e.event_time <= c.viewed_at + INTERVAL '1 day'
  GROUP BY c.user_id, c.viewed_at, c.carted_at
)
SELECT k.*, MIN(e.event_time) AS ordered_at    -- step 4: first order after the checkout
FROM checkouts k
LEFT JOIN events e
       ON e.user_id = k.user_id AND e.event = 'order'
      AND e.event_time >  k.checked_out_at
      AND e.event_time <= k.viewed_at + INTERVAL '1 day'
GROUP BY k.user_id, k.viewed_at, k.carted_at, k.checked_out_at;

Then count each column and compute the two conversion rates with LAG and FIRST_VALUE:

WITH counts AS (
  SELECT COUNT(viewed_at)      AS s1,
         COUNT(carted_at)      AS s2,
         COUNT(checked_out_at) AS s3,
         COUNT(ordered_at)     AS s4
  FROM strict_funnel_users
)
SELECT step, users,
       ROUND(100.0 * users / LAG(users) OVER (ORDER BY step_no), 1)         AS step_conversion_pct,
       ROUND(100.0 * users / FIRST_VALUE(users) OVER (ORDER BY step_no), 1) AS overall_conversion_pct
FROM counts,
     LATERAL (VALUES (1, 'product_view', s1), (2, 'add_to_cart', s2),
                     (3, 'checkout', s3),     (4, 'order', s4)) AS t(step_no, step, users)
ORDER BY step_no
stepusersstep_conversion_pctoverall_conversion_pct
product_view5006NULL100.0
add_to_cart147329.429.4
checkout81355.216.2
order56769.711.3

Only 567 viewers (11.3%) completed every step in order within a day, against 974 in the naive count. Step by step, the biggest leak is product view → cart (29.4%), and the next is cart → checkout (55.2%).

Bar chart comparing two funnel queries on the same July sale-week event log of 5,006 viewers. Unordered counts: 1,659 add to cart, 1,500 checkout, 974 orders, 19.5% conversion. Strict ordered funnel within 1 day: 1,473 add to cart, 813 checkout, 567 orders, 11.3% conversion.

Where did 407 buyers go?

974 people ordered, but only 567 show up at the end of the strict funnel. Before calling one query "wrong", find out who the missing buyers are:

WITH buyers AS (
  SELECT user_id, MIN(event_time) FILTER (WHERE event = 'product_view') AS viewed_at
  FROM events
  GROUP BY user_id
  HAVING COUNT(*) FILTER (WHERE event = 'order') > 0
),
carts AS (
  SELECT b.user_id,
         COUNT(e.*)                                  AS cart_events,
         COUNT(e.*) FILTER (WHERE e.event_time > b.viewed_at) AS carts_after_view
  FROM buyers b
  LEFT JOIN events e ON e.user_id = b.user_id AND e.event = 'add_to_cart'
  GROUP BY b.user_id
)
SELECT COUNT(*) AS buyers,
       COUNT(*) FILTER (WHERE cart_events = 0)                         AS no_cart_event,
       COUNT(*) FILTER (WHERE cart_events > 0 AND carts_after_view = 0) AS cart_only_before_view,
       (SELECT COUNT(*) FROM strict_funnel_users WHERE ordered_at IS NOT NULL) AS in_strict_funnel
FROM carts
buyersno_cart_eventcart_only_before_viewin_strict_funnel
974221186567

221 + 186 + 567 = 974, so every buyer is accounted for:

  • 221 buyers have no cart event at all. They used Buy Now, which goes straight from the product page to checkout. A funnel that requires a cart step can never count them.
  • *186 buyers only have a cart event from before their product view.* These are items synced from a wishlist or added days earlier. The order rule rejects the cart step, so the funnel stops at step 1.

Neither group did anything wrong. The funnel definition didn't match how people actually shop. So run a second funnel with the cart optional: view → checkout → order, in order, within a day.

WITH views AS (
  SELECT user_id, MIN(event_time) AS viewed_at
  FROM events WHERE event = 'product_view'
  GROUP BY user_id
),
checkouts AS (
  SELECT v.user_id, v.viewed_at, MIN(e.event_time) AS checked_out_at
  FROM views v
  LEFT JOIN events e
         ON e.user_id = v.user_id AND e.event = 'checkout'
        AND e.event_time >  v.viewed_at
        AND e.event_time <= v.viewed_at + INTERVAL '1 day'
  GROUP BY v.user_id, v.viewed_at
),
done AS (
  SELECT k.*, MIN(e.event_time) AS ordered_at
  FROM checkouts k
  LEFT JOIN events e
         ON e.user_id = k.user_id AND e.event = 'order'
        AND e.event_time >  k.checked_out_at
        AND e.event_time <= k.viewed_at + INTERVAL '1 day'
  GROUP BY k.user_id, k.viewed_at, k.checked_out_at
)
SELECT COUNT(viewed_at) AS viewers,
       COUNT(checked_out_at) AS checkouts,
       COUNT(ordered_at) AS orders,
       ROUND(100.0 * COUNT(ordered_at) / COUNT(viewed_at), 1) AS overall_conversion_pct
FROM done
viewerscheckoutsordersoverall_conversion_pct
5006140797419.5

That gets back all 974 buyers. What to report: both funnels, clearly labelled. The cart funnel (11.3%) measures the classic "browse, add to cart, buy" path, and that's where you look for drop-off. The cart-optional funnel (19.5%) measures total conversion. And Buy Now is now visibly carrying almost a quarter of orders (221 of 974), which is worth knowing on its own.

Funnel by city tier

The last part of the brief: is checkout worse in smaller cities? Because the view keeps one row per user, splitting by any user column is one join:

SELECT u.city_tier,
       COUNT(f.viewed_at) AS viewers,
       ROUND(100.0 * COUNT(f.carted_at)      / COUNT(f.viewed_at), 1)        AS view_to_cart_pct,
       ROUND(100.0 * COUNT(f.checked_out_at) / NULLIF(COUNT(f.carted_at), 0), 1) AS cart_to_checkout_pct,
       ROUND(100.0 * COUNT(f.ordered_at)     / NULLIF(COUNT(f.checked_out_at), 0), 1) AS checkout_to_order_pct,
       ROUND(100.0 * COUNT(f.ordered_at)     / COUNT(f.viewed_at), 1)        AS overall_pct
FROM strict_funnel_users f
JOIN users u USING (user_id)
GROUP BY u.city_tier
ORDER BY u.city_tier
city_tierviewersview_to_cart_pctcart_to_checkout_pctcheckout_to_order_pctoverall_pct
Tier 1171130.352.474.611.9
Tier 2167331.557.373.513.3
Tier 3162226.356.059.48.8

Tier 3 users add to cart a bit less often (26.3%), but the real gap is the last step: only 59.4% of Tier 3 checkouts become orders, against about 74% in Tier 1 and Tier 2. That points to something on the payment or delivery screen, such as payment options, cash-on-delivery limits, delivery dates or the final price with shipping, rather than to product discovery. SQL tells you where the leak is. The next step is to look at the checkout screen for Tier 3 users or run an A/B test on a fix (see our A/B testing guide).

Turning it into a stakeholder readout

A good readout is three findings and one recommendation:

1. Sale signups don't stick. The April sale doubled signups, and 52.7% of sale users ordered in the first month, but only 17.9% were still ordering by month 2, against 31.9% for organic users. Judge future sales on month-2 retention, not signups.

2. Retention is steady otherwise. The other cohorts keep 37–41% of signups in month 1 and 31–33% in month 2. The "July drop" on the current dashboard is a half-month artefact.

3. Checkout leaks in Tier 3. Checkout → order is 59.4% in Tier 3 vs about 74% elsewhere. 23% of all orders come through Buy Now, so the cart-based funnel undercounts conversion.

Recommendation: investigate and test the Tier 3 payment step first. It's the biggest fixable gap closest to revenue.

Cohort retention SQL in MySQL, SQL Server, BigQuery and others

The logic is the same everywhere. Only the date functions and the pivot syntax change. Use these on dates already truncated to the first of the month:

DatabaseCohort monthMonths between a and bPivot a count
PostgreSQLDATE_TRUNC('month', d)EXTRACT(YEAR FROM AGE(b, a)) * 12 + EXTRACT(MONTH FROM AGE(b, a))COUNT(*) FILTER (WHERE …)
MySQL 8DATE_FORMAT(d, '%Y-%m-01')TIMESTAMPDIFF(MONTH, a, b)SUM(CASE WHEN … THEN 1 ELSE 0 END)
SQL ServerDATETRUNC(month, d) (2022+)DATEDIFF(month, a, b)SUM(CASE WHEN … THEN 1 ELSE 0 END)
BigQueryDATE_TRUNC(d, MONTH)DATE_DIFF(b, a, MONTH)COUNTIF(…)
SnowflakeDATE_TRUNC('month', d)DATEDIFF('month', a, b)COUNT_IF(…)
DuckDBdate_trunc('month', d)date_diff('month', a, b)COUNT(*) FILTER (WHERE …)
SQLitedate(d, 'start of month')(strftime('%Y', b) - strftime('%Y', a)) * 12 + strftime('%m', b) - strftime('%m', a)COUNT(*) FILTER (WHERE …)

We ran the PostgreSQL version for this post and tested the SQLite month formula on SQLite 3.51. The other rows come from each database's documentation (linked in Sources). Careful with day-level differences: SQL Server's DATEDIFF(month, …) counts month boundaries crossed, so 31 January to 1 February is "1 month". That's harmless on month starts but misleading on raw dates.

In Excel, Power BI or Tableau? Do the cohort assignment and month number in SQL (or Power Query), then build the matrix as a pivot table, a Power BI matrix visual or a Tableau highlight table with cohort month on rows and month number on columns. In pandas, the same logic is groupby + unstack, as in our pandas dates and time series lesson.

Common cohort and funnel analysis mistakes

MistakeWhat goes wrongFix
COUNT(*) instead of COUNT(DISTINCT user_id)Repeat buyers counted several times. Jan month 0 showed 48.6% instead of 41.6%Deduplicate to one row per user per period first
Base = month-0 buyers, not signupsMonth-1 "retention" of 89.3% instead of 37.2%Divide by the full cohort size, and label which base you use
Half-finished periods shown as completeA fake "drop" along the July diagonal, about half of normalLeave out or grey out periods after the snapshot date
Mixing calendar months and day windows"Month 1" means different things on different chartsPick one definition per report and name it in the title
Inner join from cohorts to ordersUsers with no orders vanish from the baseBuild the cohort size from users, not from purchases
Unordered funnel19.5% "conversion" when the strict path was 11.3%Require each step after the previous one, within a window
Forcing one fixed pathBuy Now and wishlist buyers disappear (407 of 974 here)Check who's missing and add an optional-step funnel
No time windowA checkout three weeks later counts as the same journeySet a conversion window (we used 1 day)
Comparing cohorts of very different sizes in raw countsBig cohorts look "better"Always compare percentages, and show the cohort size
Blending sources in one cohortA sale cohort hides a weak segment behind a strong oneSplit by source, campaign or city tier

Cohort and funnel analysis interview questions

These come up in data analyst, product analyst and data scientist SQL rounds in India. Each answer uses this project.

1. Write a query for monthly cohort retention. "Assign each user a cohort with DATE_TRUNC('month', signup_date), compute the month number of each order since the cohort month, keep distinct users per cohort and month number, and divide by the cohort size from the users table. Then pivot month numbers into columns."

2. How can retention go above 100%? "Either by counting orders instead of distinct users, or by dividing by a smaller base than the cohort, such as month-0 buyers. In our data, dividing by month-0 buyers turned a real 37.2% month-1 retention into 89.3%."

3. The latest month looks terrible for every cohort. What do you check first? "Whether the month is complete. If the data was pulled mid-month, the whole latest diagonal is half-empty. I exclude periods after the snapshot date or label them."

4. Calendar-month retention or 30-day windows? "Calendar months match monthly reporting and are easy to explain. Day windows treat every user the same regardless of signup date. I pick one and say which in the title, because they give different numbers."

5. How is a funnel query different from counting events? "A funnel checks that each user did the steps in order, within a time window. Counting events per step ignores both, so it overstates conversion. Ours showed 19.5% vs 11.3%."

6. How do you write an ordered funnel in SQL? "Take each user's first timestamp for step 1, then LEFT JOIN the next event with event_time > previous_step_time and within the window, take MIN, and repeat. Count the non-null columns, then use LAG for step conversion and FIRST_VALUE for overall conversion."

7. Your strict funnel shows fewer orders than the orders table. Why? "Users who skipped a step, like Buy Now skipping the cart, or whose events are out of order, like a wishlist item added to cart before the session. I'd find them with a breakdown query and add a funnel with the optional step."

8. A sale brought in many new users. How do you judge if it worked? "Compare sale signups with organic signups from the same month on month-1 and month-2 retention, and on revenue per user, not just signups. Here sale users ordered more in month 0 (52.7% vs 40.8%) but retained far worse by month 2 (17.9% vs 31.9%)."

9. What is Day-7 or Day-30 retention? "The share of a cohort active on, or in a window around, day 7 or day 30 after their start. In e-commerce I'd often use repeat purchase within 30 days of the first order, which was 27–31% here."

10. Where would you look first for a conversion problem? "The step with the lowest step conversion that's closest to revenue, split by segment. Here that was checkout → order in Tier 3, at 59.4% vs about 74% elsewhere."

More practice: SQL interview questions, data analyst interview questions and the window functions guide.

How to show this project on your resume

  • "Built monthly cohort retention and ordered checkout funnel analyses in PostgreSQL on 7,200 users and 10,506 orders (CTEs, window functions, date functions); found that sale-week signups kept 17.9% by month 2 vs 31.9% for organic users."
  • "Showed that an unordered funnel overstated conversion (19.5% vs 11.3%), traced 407 'missing' buyers to Buy Now and wishlist paths, and located the largest leak at Tier 3 checkout → order (59.4% vs 74%)."

Say the data is simulated if it is, and link the SQL on GitHub. More ideas in data analysis projects and writing a data analyst resume.

Key takeaways

  • A cohort retention table is active users ÷ cohort size, per cohort and period. The base is everyone who started, not only buyers.
  • Use COUNT(DISTINCT user_id), never COUNT(*) on orders.
  • Leave out or label periods that haven't finished. Half a month of data makes the whole latest diagonal look like a crash.
  • Pick one retention definition (calendar month, day window, unbounded or repeat purchase) and name it.
  • Split cohorts by source. Our April sale cohort was twice as big but retained about half as well by month 2.
  • A real funnel checks order and a time window. Report the strict path and a total-conversion funnel, and explain who's in the gap.

Frequently asked questions

What is cohort analysis in SQL?

Cohort analysis in SQL groups users by a shared starting point, usually their signup month with DATE_TRUNC('month', signup_date), and then measures what share of each group is active in each later period. The usual output is a retention table with one row per cohort and one column per month number, built with CTEs, COUNT(DISTINCT user_id) and a pivot.

How do you calculate cohort retention rate?

Retention rate for period N = users from the cohort who were active in period N ÷ total users in the cohort. For example, 368 of the 990 users who signed up in January ordered in February, so January's month-1 retention is 368 ÷ 990 = 37.2%. The denominator is everyone in the cohort, including users who never ordered.

What is month 0 in a retention table?

Month 0 is the cohort's own starting month: for a January cohort, it's activity in January. It's often the highest value because many users act right after signing up, and it covers only the days left in the month after each user's signup.

How do you write a funnel analysis query in SQL?

Find each user's first timestamp for the first step. For every next step, LEFT JOIN the events table on the same user where the event happened after the previous step and inside a time window, and take MIN(event_time). Count the non-null timestamp for each step, then divide each count by the previous step for step conversion and by the first step for overall conversion.

What is the difference between an ordered and an unordered funnel?

An unordered funnel counts users who did each event at any time, in any order. An ordered funnel counts a step only if it happened after the previous step, usually within a time window. Unordered funnels overstate conversion. On our data, the unordered funnel showed 19.5% of viewers ordering and the ordered funnel showed 11.3%.

Why does my retention table show a drop in the latest month?

Usually because the latest month isn't over. If data was pulled on the 15th, every cohort has only half a month of activity in that column, so the whole latest diagonal looks low. Exclude or label periods after the data snapshot date.

What is the difference between retention and churn?

Retention is the share of a cohort still active in a period. Churn is the share that has stopped being active. For a single period they add up to 100% if every user is either active or not, but churn is often defined over a window (for example, no order in 60 days), so check the definition. Our churn prediction project shows how to predict who will churn.

Which SQL functions are used in cohort analysis?

DATE_TRUNC (or its equivalent) to build the cohort month, a month difference function such as AGE in PostgreSQL, DATEDIFF in SQL Server or DATE_DIFF in BigQuery, COUNT(DISTINCT), CTEs to break the query into steps, joins to attach the cohort size, and FILTER or CASE WHEN to pivot month numbers into columns. Window functions such as LAG and FIRST_VALUE help with funnel conversion rates.

Can I do cohort analysis in Excel or Power BI instead of SQL?

Yes. Compute each user's cohort month and each order's month number (in SQL, Power Query or Excel formulas), then build a pivot table or a Power BI matrix with cohort month on rows, month number on columns and distinct users as values. Divide by the cohort size to get percentages. For large event tables, doing the heavy lifting in SQL first is faster.

Is cohort analysis asked in data analyst interviews?

Yes. Monthly cohort retention and funnel conversion are among the most common SQL case questions for data analyst, product analyst and data scientist roles at product companies, because they test CTEs, date handling, joins, COUNT(DISTINCT) and window functions in one problem. Interviewers often follow up with "why can retention exceed 100%?" or "why is the latest month low?".

Recommended reading and practice on Skillancy

Practice: SQL interview questions · SQL compiler

Sources

Reproducibility note

Every query and output on this page was produced on 2 December 2026 by running the dataset script and then the queries, in order, on PGlite 0.5.5 (PostgreSQL 18.3 compiled to WebAssembly, the same engine as the Skillancy SQL compiler) on an Apple M1 Pro laptop. The data is simulated with setseed(0.42), so the same script gives the same rows. The SQLite month formula was tested separately on SQLite 3.51.0. Syntax for other databases comes from their documentation. The two charts were drawn from the query outputs. The sale effect, the Buy Now share and the Tier 3 checkout gap were built into the simulation on purpose, so the queries have something real to find.

Learn it live: cohort retention and funnel queries are taught hands-on in week 2 of Data Science with AI, where you build this Meesho product funnel and cohort retention analysis as a graded project, then go on to statistics, machine learning and AI agents. For the analyst path, Data Analytics with Agentic AI covers the same CTEs and window functions in its Flipkart and Myntra SQL projects, plus Excel, Tableau and Power BI. Not sure which fits you? Talk to a mentor. Learn. Build. Get hired.
Newsletter

Get the Skillancy field notes

One email a week: AI and analytics guides, cohort dates and hiring signals. No spam, unsubscribe anytime.