SQL Customer Lifetime Value

A per-user SUM of everything they've ever spent — simple math, meaningful framing.

What & Why

Customer Lifetime Value estimates the value a customer generates across the relationship, usually from revenue, margin, frequency, and lifespan inputs. CLV guides acquisition spending only when every input and assumption is documented.

See How It Works

BUSINESS QUESTION

Calculate observed lifetime paid-invoice value for every SaaS account without inventing future revenue.

idnameplanmrrcreated_atchurned_atcountryemployee_countindustry
1Acme Labsgrowth240.002024-01-08 10:00:00+00NULLUS45software
2Northstar Costarter90.002024-02-12 09:30:00+002024-05-18 12:00:00+00CA18services
3Atlas Worksscale480.002024-03-04 15:10:00+00NULLGB120manufacturing
4Bright Pathgrowth180.002024-04-19 11:45:00+00NULLUS62education
idaccount_idamountstatusdue_datepaid_at
101240.00paid2024-02-012024-01-29 13:00:00+00
111260.00paid2024-03-012024-02-28 16:30:00+00
12290.00overdue2024-03-15NULL
133480.00open2024-04-01NULL
EXAMPLE QUERY
SELECT
  a.id AS account_id,
  a.name,
  a.plan,
  COALESCE(SUM(i.amount) FILTER (WHERE i.status = 'paid'), 0) AS observed_lifetime_value
FROM saas.accounts a
LEFT JOIN saas.invoices i ON i.account_id = a.id
GROUP BY a.id, a.name, a.plan
ORDER BY observed_lifetime_value DESC, account_id;
RESULT — observed paid value per account
account_idnameplanobserved_lifetime_value
1Acme Labsgrowth500.00
2Northstar Costarter0
3Atlas Worksscale0
4Bright Pathgrowth0

Only Acme Labs has paid invoices in the representative data; the LEFT JOIN and COALESCE preserve the other accounts with zero value.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario