Skip to content

About

A PostgreSQL customer retention and cohort analysis project investigating repeat purchasing behaviour, weekly retention rates and customer engagement using advanced SQL queries, CTEs and date-based analysis.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Customer Retention & Cohort Analysis | PostgreSQL

SQL PostgreSQL Cohort Analysis Customer Retention

Project Overview

This project investigates customer retention, repeat purchasing behaviour and weekly cohort performance using PostgreSQL and a historical online retail transaction dataset containing more than 541,000 records.

The analysis groups customers according to their first observed qualifying purchase week and measures their subsequent weekly purchasing activity.

Through advanced SQL techniques, structured data preparation and customer-level analysis, the project transforms transactional data into meaningful commercial insights that can support customer relationship management, retention strategies and business decision-making.

Executive Summary

Key Performance Indicator Result
Original Transaction Records 541,909
Eligible Purchase Records 397,884
Excluded Records 144,025
Eligible Unique Customers 4,338
Unique Qualifying Invoices 18,532
Customers Purchasing Across Multiple Weeks 2,772
Multi-Week Purchasing Customer Percentage 63.90%
Customers With Multiple Qualifying Invoices 2,845
Identified Weekly Cohorts 53
Cohorts Included in Complete-Week Results 52
Cohort-Period Result Records 1,382

The analysis identifies substantial repeat purchasing activity while highlighting variation in customer engagement across reporting periods.

These results were independently calculated from the supplied dataset using the documented eligibility rules. The revised PostgreSQL query requires execution validation against the supplied results file.

Business Problem

Customer acquisition alone does not establish whether a retail organisation is developing sustainable customer relationships.

Businesses must understand whether customers return following their initial purchase, how purchasing behaviour changes over time and which customer groups demonstrate stronger ongoing engagement.

Without structured customer retention reporting, organisations may struggle to:

  • Identify changes in repeat purchasing behaviour.
  • Evaluate customer engagement following acquisition.
  • Compare customer groups across equivalent reporting periods.
  • Identify potential customer disengagement.
  • Develop targeted customer retention campaigns.
  • Allocate marketing and customer relationship management resources effectively.

This project addresses these requirements through a SQL-based customer cohort retention analysis.

Project Objectives

  • Analyse historical online retail transactions.
  • Assess data quality and identify unsuitable transaction records.
  • Establish each customer's first observed qualifying purchase.
  • Group customers into weekly acquisition cohorts.
  • Calculate original customer cohort sizes.
  • Measure subsequent weekly purchasing activity.
  • Calculate customer retention percentages.
  • Include periods with zero qualifying customer activity.
  • Exclude incomplete reporting periods.
  • Translate analytical findings into actionable business recommendations.

Tools and Technologies

Tool / Technique Application
PostgreSQL Relational database and analytical processing
SQL Data preparation and analysis
pgAdmin Database management and query execution
Common Table Expressions (CTEs) Structuring complex analytical queries
Aggregate Functions Customer and cohort calculations
DATE_TRUNC Weekly date grouping
GENERATE_SERIES Complete reporting period generation
DISTINCT Preventing duplicate customer counts
JOIN Operations Connecting customer cohorts and activity
COALESCE Handling missing activity counts
NULLIF Preventing division-by-zero errors
CSV Source data and analytical results

Dataset Overview

The project uses the Online Retail dataset published through the UCI Machine Learning Repository.

The dataset contains historical transactions from a UK-based online retailer operating between 1 December 2010 and 9 December 2011.

Dataset Characteristic Description
Source UCI Machine Learning Repository
Dataset Online Retail
Original Records 541,909
Original Columns 8
Reporting Period December 2010 – December 2011
Data Granularity Transaction-level
Analysis Frequency Weekly
Currency GBP
Dataset Licence Creative Commons Attribution 4.0

Download the Dataset

Download the Online Retail dataset from UCI

The original dataset is not duplicated within this repository due to its file size.

It remains publicly accessible through the original data provider.

The repository includes the SQL scripts required to reproduce the analysis and a CSV containing the independently calculated cohort retention results.

Dataset Structure

Source Column PostgreSQL Column Description
InvoiceNo invoice_no Transaction identifier
StockCode stock_code Product identifier
Description description Product description
Quantity quantity Transaction quantity
InvoiceDate invoice_date Transaction date and time
UnitPrice unit_price Price per product unit
CustomerID customer_id Customer identifier
Country country Customer country

Data Quality Assessment

The original dataset contains several characteristics that require consideration before conducting customer retention analysis.

Data Quality Indicator Result
Original Transaction Records 541,909
Records Missing Customer ID 135,080
Records Missing Product Description 1,454
Original Identifiable Customers 4,372
Eligible Customers After Filtering 4,338
Eligible Purchase Records 397,884

Approximately 24.93% of the original transaction records do not contain a customer identifier.

These records cannot reliably be assigned to individual customer cohorts and are therefore excluded from the retention calculations.

Missing product descriptions are not automatically excluded because product descriptions are not required for customer-level retention measurement.

Purchase Eligibility Rules

A qualifying purchase must satisfy the following conditions:

  • A valid customer identifier is present.
  • Transaction quantity is greater than zero.
  • Unit price is greater than zero.
  • The invoice number does not begin with C, indicating a cancellation.
WHERE customer_id IS NOT NULL
  AND quantity > 0
  AND unit_price > 0
  AND UPPER(invoice_no) NOT LIKE 'C%'

These conditions exclude unidentified customers, cancellation invoices and non-positive transaction records.

The original source data remains unchanged, with analytical eligibility rules applied through SQL.

Analytical Methodology

1. Database Creation and Data Import

The source dataset is imported into a PostgreSQL table named online_retail.

The database structure uses appropriate data types for transaction identifiers, product descriptions, quantities, customer identifiers and monetary values.

The original invoice date is initially stored as text to accommodate the supplied CSV timestamp format before conversion during analysis.

The database setup script is available here:

Database_Setup.sql

2. Weekly Customer Activity

Transaction dates are grouped into Monday-based calendar weeks using DATE_TRUNC.

SELECT DISTINCT
    customer_id,
    DATE_TRUNC('week', purchase_date)::date AS event_week
FROM Purchases

DISTINCT ensures that customers purchasing multiple products or placing multiple orders within the same week are counted only once for weekly retention purposes.

3. Customer Cohort Assignment

Customers are assigned to a cohort according to their first observed qualifying purchase week.

SELECT
    customer_id,
    MIN(event_week) AS signup_week
FROM Actions
GROUP BY customer_id

The original learning query refers to customer signup dates.

However, the Online Retail dataset does not contain account registration dates.

The revised methodology therefore uses the first observed qualifying purchase as a proxy for customer acquisition.

Each customer belongs to one cohort only.

4. Cohort Size Calculation

The original cohort size represents the number of distinct customers whose first qualifying purchase occurred within the relevant calendar week.

SELECT
    signup_week,
    COUNT(*) AS cohort_size
FROM Signups
GROUP BY signup_week

The original cohort size remains the denominator throughout the subsequent retention calculations.

5. Returning Customer Identification

Customer cohorts are connected to subsequent purchasing activity using SQL JOIN operations.

SELECT
    s.signup_week,
    a.event_week,
    COUNT(DISTINCT a.customer_id) AS retained_customers
FROM Signups s
JOIN Actions a
    ON s.customer_id = a.customer_id
   AND a.event_week >= s.signup_week
GROUP BY
    s.signup_week,
    a.event_week

This identifies the number of distinct customers from each original cohort who recorded qualifying purchasing activity during each subsequent week.

6. Complete Reporting Period Generation

The revised analysis uses PostgreSQL's GENERATE_SERIES function to generate a complete weekly reporting structure.

This ensures that reporting periods with no qualifying customer activity are represented explicitly rather than omitted.

COALESCE converts missing activity counts into zero.

The final incomplete calendar week is excluded to improve comparability between reporting periods.

7. Weekly Retention Calculation

Weekly retention is calculated using the following formula:

Retention Rate = Returning Customers / Original Cohort Size × 100

The corresponding SQL calculation is:

ROUND(
    100.0 * COALESCE(r.retained_customers, 0)
    / NULLIF(c.cohort_size, 0),
    2
) AS percentage_retained

NULLIF protects the calculation against division-by-zero errors.

Week zero represents the initial purchase week and therefore has a retention rate of 100%.

Subsequent weeks represent the proportion of the original cohort recording qualifying purchases during the relevant reporting period.

Customers may return after periods of inactivity. Consequently, this metric measures periodic purchasing activity rather than uninterrupted customer survival.

SQL Query Architecture

The revised SQL analysis uses seven interconnected common table expressions.

CTE Analytical Purpose
Purchases Filters and prepares qualifying purchase records
Actions Identifies distinct weekly customer activity
Signups Establishes each customer's first observed purchase week
Cohort Calculates original customer cohort sizes
Retained Identifies subsequent purchasing activity
Reporting_End Determines the final incomplete reporting week
Cohort_Weeks Generates complete weekly observation periods

The final SELECT statement combines these calculations into a structured retention reporting dataset.

Analytical Workflow

flowchart TD
    A[Raw Retail Transactions] --> B[Filter Qualifying Purchases]
    B --> C[Identify Weekly Customer Activity]
    C --> D[Assign Customer Cohorts]
    D --> E[Calculate Cohort Sizes]
    C --> F[Identify Returning Customers]
    D --> F
    E --> G[Generate Reporting Weeks]
    F --> H[Calculate Weekly Retention]
    G --> H
    H --> I[Customer Retention Insights]
Loading

Key Analytical Findings

1. Significant Repeat Purchasing Activity

Of the 4,338 eligible customers, 2,772 recorded qualifying purchases across more than one distinct calendar week.

This represents approximately 63.90% of eligible customers.

Additionally, 2,845 customers recorded more than one distinct qualifying invoice.

The distinction is important because customers may place multiple orders during their initial purchase week without returning during subsequent weeks.

Business implication: Measuring purchasing frequency alongside weekly retention provides a more comprehensive understanding of customer engagement than relying exclusively on transaction volume.

2. Customer Identification Is a Significant Data Quality Issue

The dataset contains 135,080 transaction records without customer identifiers.

These records represent approximately one-quarter of the original dataset.

Although these transactions may contain valid commercial activity, they cannot reliably support customer-level retention tracking.

Business implication: Improving customer identification practices could strengthen the completeness of customer analytics, customer segmentation and relationship management reporting.

3. Initial Customer Cohort Performance

The first observed customer cohort begins on Monday 29 November 2010 and contains 303 eligible customers.

Weeks Since First Purchase Cohort Size Purchasing Customers Retention Rate
0 303 303 100.00%
1 303 65 21.45%
2 303 73 24.09%
3 303 20 6.60%
4 303 0 0.00%
5 303 60 19.80%
6 303 47 15.51%
7 303 45 14.85%

The results demonstrate that weekly purchasing activity does not necessarily decline at a consistent rate.

Retention increases between weeks one and two and subsequently recovers following a reporting week with no qualifying customer activity.

Business implication: Customer inactivity during a particular week should not automatically be classified as permanent customer loss.

Seasonality, purchasing cycles and business operating patterns should be investigated before drawing conclusions about customer disengagement.

4. Complete Reporting Periods Improve Comparability

The dataset contains 53 identified first-purchase cohorts.

The complete-week retention analysis includes 52 cohorts and 1,382 cohort-period observations.

The final observed calendar week is excluded because the dataset ends before that reporting week finishes.

Business implication: Excluding incomplete reporting periods reduces the risk of incorrectly interpreting partial data as declining customer engagement.

5. Cohort Analysis Supports More Meaningful Customer Comparisons

Different customer cohorts contain different numbers of customers and have different available observation periods.

Comparing cohorts using retention percentages rather than absolute customer counts helps standardise performance comparisons.

However, cohort size and available observation periods remain important considerations when interpreting the results.

Business implication: Customer retention reports should present both customer counts and retention percentages to provide sufficient context for commercial decision-making.

Business Recommendations

Analytical Finding Recommended Action Potential Business Benefit
Significant repeat purchasing activity Investigate characteristics of returning customers More targeted customer engagement
Early purchasing activity varies Test post-purchase follow-up campaigns Encourage subsequent purchases
Missing customer identifiers Improve transaction-level customer identification More complete customer reporting
Customers return following inactive periods Investigate normal purchasing cycles More accurate customer segmentation
Different cohort sizes Monitor customer counts alongside retention percentages More reliable performance comparisons
Incomplete reporting periods Standardise reporting cut-off dates Improved analytical consistency
Historical purchasing fluctuations Investigate seasonal and operational patterns Better-informed commercial decisions

These recommendations represent potential business actions arising from the analysis rather than implemented initiatives or confirmed financial benefits.

Practical Business Applications

Customer Relationship Management

  • Identify opportunities for targeted customer engagement.
  • Monitor purchasing behaviour following initial acquisition.
  • Investigate inactive and returning customer segments.

Commercial Analysis

  • Assess customer purchasing frequency.
  • Identify differences between customer acquisition groups.
  • Support sustainable revenue and customer engagement strategies.

Marketing Analytics

  • Evaluate potential timing for customer engagement campaigns.
  • Identify opportunities for customer reactivation.
  • Establish a foundation for campaign effectiveness measurement.

Management Information Reporting

  • Develop repeatable customer retention metrics.
  • Compare customer activity across consistent reporting periods.
  • Support structured customer performance reporting.

Original Query and Technical Improvements

The original SQL learning exercise used common table expressions to connect customer signup cohorts with subsequent activity.

The revised portfolio version retains this analytical approach while addressing differences between the original query assumptions and the available dataset.

Original Approach Revised Approach
Signup date assumed to exist First observed purchase used as acquisition proxy
Signup week assumed to exist Cohort week derived through SQL
All recorded activity considered Qualifying purchase eligibility rules applied
Observed activity weeks only Complete weekly reporting periods generated
Retention percentage output Cohort sizes, customer counts and percentages included
Incomplete weeks not explicitly handled Final incomplete calendar week excluded
Zero-activity periods potentially omitted Zero activity explicitly represented

The original SQL query is retained separately to demonstrate the initial analytical approach and subsequent technical refinement.

The revised SQL and independently calculated results were prepared with AI-assisted technical review.

Analytical Limitations

  • The dataset represents historical purchasing activity from 2010 to 2011.
  • Actual customer registration dates are unavailable.
  • First observed purchases may not represent genuine first-ever purchases.
  • Customer purchasing history before the dataset's start date is unknown.
  • The initial reporting week begins before the first available transaction date.
  • Transactions without customer identifiers cannot reliably support customer-level retention analysis.
  • Non-positive transactions and cancellation invoices are excluded.
  • Customer inactivity does not necessarily indicate permanent customer loss.
  • Customers may purchase infrequently due to normal purchasing requirements.
  • Later cohorts have shorter available observation periods.
  • The final incomplete calendar week is excluded.
  • Retention percentages do not account for customer revenue or profitability.
  • Observed patterns do not establish causal relationships.
  • The revised PostgreSQL query should be reconciled against the independently calculated results.

Opportunities for Further Development

Potential extensions include:

  • Monthly customer retention analysis.
  • Customer lifetime value analysis.
  • Recency, frequency and monetary value (RFM) segmentation.
  • Revenue retention analysis.
  • Customer purchasing frequency segmentation.
  • Country-specific retention analysis.
  • Product-category retention analysis.
  • Customer reactivation analysis.
  • Seasonal purchasing analysis.
  • Weighted retention benchmarks across cohorts.
  • Power BI cohort retention heatmaps.
  • Automated customer performance reporting.

Repository Structure

File Description
Database_Setup.sql PostgreSQL table creation and import instructions
Customer_Retention_Analysis.sql Revised customer cohort retention query
Original_Cohort_Query.sql Original SQL learning exercise
Cohort_Retention_Results.csv Independently calculated weekly retention results
README.md Project documentation and analytical findings

The original transaction dataset is available through the UCI Machine Learning Repository and is not duplicated within this repository.

How to Reproduce the Analysis

Prerequisites

  • PostgreSQL
  • pgAdmin or another PostgreSQL-compatible database client
  • Online Retail dataset
  • Spreadsheet software for CSV conversion if required

Step 1 — Download the Source Data

Download the dataset from:

https://archive.ics.uci.edu/dataset/352/online+retail

If the source is provided in Excel format:

  1. Open the original Excel workbook.
  2. Export the transaction worksheet as a CSV file.
  3. Name the file Online_Retail.csv.
  4. Preserve the original eight-column order.
  5. Ensure invoice dates are formatted consistently with the parsing rules in the SQL script.
  6. Preserve blank customer identifiers.

Step 2 — Database Setup

  1. Download the SQL scripts from this repository.
  2. Create a PostgreSQL database named customer_retention.
  3. Open Database_Setup.sql in the database query tool.
  4. Execute the CREATE TABLE statement.
  5. Import Online_Retail.csv into the online_retail table.
  6. Enable the CSV header option during import.
  7. Select the encoding appropriate for the downloaded CSV.
  8. Ensure blank customer identifiers are imported as NULL values.
  9. Confirm the source table contains 541,909 records.

Step 3 — Execute the Analysis

  1. Open Customer_Retention_Analysis.sql.
  2. Execute the complete SQL query.
  3. Review the customer cohort and reporting week columns.
  4. Review original cohort sizes.
  5. Review returning customer counts.
  6. Review the calculated retention percentages.
  7. Export the query results if required.
  8. Compare the results against Cohort_Retention_Results.csv.

Expected Validation Checks

Validation Check Expected Result
Original Transaction Records 541,909
Qualifying Purchase Records 397,884
Eligible Unique Customers 4,338
Identified Weekly Cohorts 53
Complete-Week Cohorts 52
Cohort-Period Output Records 1,382
Week-Zero Retention 100%
Minimum Possible Retention 0%
Maximum Possible Retention 100%

Returning customer counts should never exceed the original cohort size.

The supplied results CSV was independently generated using equivalent analytical rules in Python.

Skills Demonstrated

Technical Skills

  • PostgreSQL
  • SQL query development
  • Common table expressions
  • SQL joins
  • Aggregate functions
  • Date and timestamp manipulation
  • Customer cohort assignment
  • Distinct customer counting
  • Complete reporting period generation
  • Null value handling
  • Conditional data filtering
  • Analytical calculations
  • Database table design
  • Data quality assessment
  • Structured SQL documentation

Business and Analytical Skills

  • Customer retention analysis
  • Customer behaviour interpretation
  • Repeat purchasing analysis
  • Cohort performance measurement
  • Commercial analysis
  • Customer relationship management insights
  • Management information reporting
  • Data quality evaluation
  • Analytical problem-solving
  • Business recommendation development
  • Critical evaluation of analytical limitations

Conclusion

This project demonstrates how PostgreSQL can transform historical retail transaction records into structured customer retention insights.

By combining customer cohort assignment, weekly purchasing activity, distinct customer aggregation and complete reporting periods, the analysis establishes a repeatable approach to measuring customer engagement.

The findings highlight substantial repeat purchasing activity, variation in weekly cohort performance and the importance of reliable customer identification when developing commercial reporting.

The project demonstrates practical SQL and analytical capabilities relevant to data analysis, management information, reporting, customer analytics, commercial analysis and business intelligence roles.

Data Source and Acknowledgements

Dataset Citation

Chen, D. (2015). Online Retail [Dataset]. UCI Machine Learning Repository.

Original Dataset

https://archive.ics.uci.edu/dataset/352/online+retail

DOI

https://doi.org/10.24432/C5BW33

Dataset Licence

https://creativecommons.org/licenses/by/4.0/

The original dataset is distributed under the Creative Commons Attribution 4.0 International licence.

The dataset is referenced through its original public source rather than duplicated within this repository.

This project was developed as a SQL learning and professional portfolio exercise. The original query is preserved separately, with AI-assisted technical review, revised SQL and independent results calculations documented transparently.

This project is intended for educational and professional portfolio demonstration purposes.

About

A PostgreSQL customer retention and cohort analysis project investigating repeat purchasing behaviour, weekly retention rates and customer engagement using advanced SQL queries, CTEs and date-based analysis.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors