Whether you’re selling groceries, financial services, or gym memberships,
successful recruitment of new customers is only truly successful if they return
to buy from you again. The metric that reflects this is called retention,
and the approach we use is customer retention analysis. Retention analysis
is typically done using cohort analysis.
Cohort analysis is a technique to see how variables change over in different
groups with different starting conditions. Retention is a simplified one, where
the starting condition is usually the time of signup and the variable is
simply activity.
It’s usually visualized as a cohort grid or retention curves.
Cohort retention analysis is pretty hard to do in SQL. We need to have the
user-date combination, which tells us about a user’s activity on that date,
including dates with no activity. To do this, we need to make a tricky join,
which gives us a dates list. Once we have it, we can “fill it” with users’
activities.
The example below shows monthly cohort retention. The same technique can be used
for daily or weekly retention.
The SQL code in this guide is Postgres-compliant. The final SQL code may be
different depending on your database. Also, this technique requires at least 1
user to be active during the month, otherwise this month will not be included in
the months’ list.
The SQL above provides the base table for our retention cube. It would show
signup months and activity months with pageviews:
Now we can calculate a total count of users and the total count of active users,
who has more than 0 page views, for every month. Based on these two measures we
can calculate monthly percentage_of_active.
To be able to build cohorts, we need to group by two dimensions: signup
date, which will define our cohorts, and months since signup, which will
show how the percentage of active users is changing.
Note, we are explicitly setting the signup_month timezone. date_trunc
returns UTC dates and not setting a correct timezone would lead to wrong results
due to time shift.