What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To calculate customer retention in SQL, define what counts as a customer, a qualifying activity, and a reporting period; assign each customer to a cohort based on a starting event such as their first purchase; then count distinct cohort members active in each later period and divide by the cohort’s period-zero size. The result is meaningful only when the activity rule, denominator, time zone, and treatment of returning customers are explicit.

How do I calculate customer retention in SQL?

A retention rate is not a universal percentage. It describes a defined population of customers and the share that meets a defined activity rule during a defined period. Before writing SQL, settle these choices:

  • Population: Which customers qualify, and what event places them in the analysis?
  • Activity: What counts as active—purchase, login, paid invoice, subscription, or another event?
  • Period: Are you measuring by day, week, or calendar month, and in which reporting time zone?
  • Denominator: Is the comparison against customers who entered the cohort at period zero?
  • Return rule: Does a customer count as retained after any later activity, or must they remain active without a gap?

The example below uses PostgreSQL and assumes a table named customer_events(customer_id, event_ts, event_type, amount). It treats a purchase as qualifying activity and cohorts customers by their first purchase month. Replace that filter and cohort rule to match the question your business needs to answer.

Build a monthly cohort-retention query

WITH activity AS (
  SELECT DISTINCT
         customer_id,
         date_trunc('month', event_ts) AS activity_month
  FROM customer_events
  WHERE event_type = 'purchase'
), cohorts AS (
  SELECT customer_id, MIN(activity_month) AS cohort_month
  FROM activity
  GROUP BY customer_id
), cohort_activity AS (
  SELECT a.customer_id,
         c.cohort_month,
         a.activity_month,
         (EXTRACT(YEAR FROM age(a.activity_month, c.cohort_month)) * 12
          + EXTRACT(MONTH FROM age(a.activity_month, c.cohort_month)))::int AS month_number
  FROM activity a
  JOIN cohorts c USING (customer_id)
), counts AS (
  SELECT cohort_month, month_number,
         COUNT(DISTINCT customer_id) AS retained_customers
  FROM cohort_activity
  GROUP BY cohort_month, month_number
), sizes AS (
  SELECT cohort_month, retained_customers AS cohort_size
  FROM counts
  WHERE month_number = 0
)
SELECT c.cohort_month,
       c.month_number,
       c.retained_customers,
       s.cohort_size,
       c.retained_customers::numeric / NULLIF(s.cohort_size, 0) AS retention_rate
FROM counts c
JOIN sizes s USING (cohort_month)
ORDER BY c.cohort_month, c.month_number;

The query has four stages: it deduplicates customer activity within each month, finds each customer’s first qualifying month, assigns later activity a month number relative to that cohort, and divides each period’s distinct-customer count by the cohort’s period-zero count. The rate is returned as a decimal; multiply by 100 for a percentage display. Counts are included so a rate can be assessed alongside the number of customers behind it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

This is an illustrative PostgreSQL pattern, not a schema-independent recipe. If activity means a successful paid invoice rather than an order attempt, filter for the event that represents payment. If the intended outcome is product engagement, a login or session may be more appropriate. State that choice with the metric.

How do I build a cohort retention table?

A cohort is a group of customers who share a starting period, commonly the month of their first purchase. A cohort table then compares activity in elapsed periods: month 0 is the cohort’s starting month, month 1 is the next calendar month, and so on. Each cell should be traceable to a customer count and the cohort size used as its denominator.

Output field Meaning
cohort_month The month in which customers first met the cohort-entry rule.
month_number Elapsed calendar months after the cohort month; 0 is the starting month.
retained_customers Distinct cohort customers with qualifying activity in that elapsed month.
cohort_size Distinct customers active in period 0, used as the denominator for that cohort.
retention_rate retained_customers / cohort_size.

For presentation, pivot the query’s rows into a matrix with one cohort per row and elapsed periods as columns. Keep the counts available even if the published view emphasizes percentages: a seemingly strong rate from a very small cohort is less stable than the same rate from a much larger one. When judging a mature period, consider the absolute number retained, the rate, and the business outcome the metric is intended to predict.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Recent cohorts need special care. A cohort created last month has not had the same opportunity to produce month-6 activity as a cohort created much earlier. Exclude periods that are not fully observable or label them clearly; otherwise incomplete follow-up can look like poor retention.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What PostgreSQL window functions add to retention analysis

The cohort query above uses grouping and a join rather than a window function, but window functions are useful for identifying first events, ranking events, calculating running values, and comparing a row with a prior period. PostgreSQL requires a window function’s OVER clause to specify how related rows are considered. Within it, PARTITION BY divides rows into groups, while ORDER BY sets their sequence within a group. See the PostgreSQL window-functions tutorial and the PostgreSQL window-functions reference.

For example, a window expression can number a customer’s events in timestamp order within that customer’s partition; selecting the first row can identify a first event. A windowed aggregate can calculate a running total without collapsing all rows into one grouped result. When a running calculation’s intended boundaries are not obvious from the default frame, specify the frame explicitly so the result matches the metric definition.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Retention versus churn: what is the difference?

Retention measures continued or recurring activity under a stated rule; churn measures loss under a stated rule. They are complements only when they use the same customer population, observation window, and activity definition. For example, a purchase-retention rate and a subscription-cancellation rate do not automatically add to 100%, because they may describe different events and populations.

A period-activity retention table answers: “What share of the original cohort generated at least one qualifying event in period n?” It does not establish that those customers were active in every intervening period.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should SQL handle customers who return after churning?

A customer who skips a period and later returns exposes an important definition choice. Under period-activity retention, that person counts as active in the return period, even if they were inactive before it. Under continuous survival, the person does not count as having remained active through the gap. Neither result is inherently wrong; they answer different questions.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
  • Period-activity retention: Count a cohort member if they have at least one qualifying event in the measured period.
  • Continuous survival: Count a cohort member only if they meet the activity rule in every period from the start through the measured period.
  • Reactivation: Track customers who were inactive for a defined interval and later became active again as a separate measure.

Do not label an any-activity result as continuous retention, or treat reactivation as evidence that a customer never churned. Define the inactivity interval for reactivation in the same units as the analysis period.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validation checks before interpreting a retention trend

Data and policy choices can change the shape of a cohort table as much as the SQL can. Validate these items before comparing cohorts or segments:

  • Customer identity: Confirm there is one stable customer identifier, and decide how merged or recreated accounts are handled.
  • Duplicate events: Deduplicate customer-period activity before counting customers so multiple purchases in one month do not inflate customer retention.
  • Time zone: Normalize event timestamps to one reporting time zone before deriving period boundaries. Handle daylight-saving transitions deliberately.
  • Observation completeness: Exclude or flag incomplete recent cohorts and right-censored periods—periods for which the full follow-up window has not yet elapsed.
  • Business events: Decide whether refunds, cancellations, pauses, trials, and reactivations qualify as activity or change the customer’s status.
  • Denominator reconciliation: Reconcile each period-zero cohort size against an independent customer count.
  • Manual test: Work through a small sample by hand and confirm the SQL assigns cohort months, elapsed periods, counts, and rates as expected.
  • SQL dialect: Record the database and dialect. Functions such as date_trunc, age, and interval arithmetic are not portable without adaptation.

Compare cohorts without hiding meaningful differences

Once the base definition is stable, compare cohorts by elapsed period and by a segment that is meaningful to the question, such as acquisition channel, plan, geography, device, or contract type. Keep segment definitions tied to a consistent point in time; a customer’s current plan may not describe the plan they had when they entered the cohort.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

If monetary values are available, customer retention and revenue or order retention can tell different stories. A cohort may retain fewer customers but produce more revenue, or preserve customer counts while order value changes. Present the metric that matches the intended business outcome rather than treating customer counts as a proxy for every kind of value.

Published case studies can illustrate implementation but should not be treated as universal benchmarks. For instance, WhitneysData’s case-study repository lists scripts for overall churn and retention, tenure-cohort retention, and advanced window functions across 7,043 customers; that is an implementation example for that dataset, not a general retention target.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.