SQL course · Module 12: Projects · Lesson 38 of 40
Quick answer: A SQL sales analytics project answers a few business questions with queries you already know. Monthly revenue is date_trunc('month', order_date) with SUM and GROUP BY. Month-over-month growth compares each month with the one before it using LAG. A cohort groups customers by signup month, and a retention table shows what share of each cohort ordered again 1, 2, 3 or more months later. A funnel counts how many sessions reach each step, from viewing a product to buying it.
In this lesson you will learn:
- how to build a reproducible sales dataset with
setseed - monthly revenue and month-over-month growth
- signup cohorts and a retention table
- a four-step funnel with conversion rates
- how CTEs, window functions,
date_trunc,GROUP BYandCASEwork together
Before you start: Lesson 37, PostgreSQL Table Partitioning for Large Tables. The project mostly reuses CTEs (Lesson 21), window functions (Lesson 24), LAG and FIRST_VALUE (Lesson 26) and CASE and date_trunc (Lesson 8).
We ran every example on PostgreSQL 16.15 in the shop database from Lesson 3 and checked the current PostgreSQL 18 manual; the queries work on newer versions too. The project adds three tables and drops them at the end. The shop tables do not change.
Table of Contents
The project: four questions
A shop opened in January 2026. In November, the owner asks:
- How much did we sell each month, and is revenue growing?
- Do customers come back after their first month?
- Do customers from referrals come back more often than customers from ads?
- Where do shoppers drop out between viewing a product and paying?
The data has three tables:
| Table | One row per | Rows |
|---|---|---|
sales_customers | customer, with signup date and channel | 4,000 |
sales_orders | order, with date, amount and status | 7,476 |
sales_events | step reached in one October shop session | 13,276 |
Build the dataset
We generate the data. As in Lesson 31, random() with a fixed setseed gives the same “random” values each time: the manual says the series “can be repeated by re-issuing setseed() with the same argument” in the same session (PostgreSQL docs: Mathematical Functions). So save the script below as practice_tables.sql and run the whole file in one session, for example with psql -U postgres -d shop -f practice_tables.sql.
The script works like this:
- Each customer gets a signup date in January to October 2026 and a channel: organic, ads or referral.
- For every month from signup to October, a customer has a chance to place one order. The chance is 70% in the signup month, then 40%, falling a little each month. Referral customers get a higher chance and ads customers a lower one.
generate_series(0, 9)(Lesson 22) gives the month numbers, and the join keeps only months up to October.- 5% of orders are refunded.
- 8,000 October sessions each reach step 1 (view a product) and maybe steps 2 to 4 (cart, checkout, purchase); mobile sessions drop out more often.
DROP TABLE IF EXISTS sales_events, sales_orders, sales_customers;
CREATE TABLE sales_customers (
id integer PRIMARY KEY,
signup_date date NOT NULL,
channel text NOT NULL -- how the customer found the shop
);
CREATE TABLE sales_orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL REFERENCES sales_customers (id),
order_date date NOT NULL,
amount numeric(10,2) NOT NULL,
status text NOT NULL -- 'completed' or 'refunded'
);
CREATE TABLE sales_events (
session_id integer NOT NULL,
device text NOT NULL,
step integer NOT NULL, -- 1 = view_product ... 4 = purchase
event text NOT NULL,
event_time timestamp NOT NULL
);
SELECT setseed(0.38); -- fixed seed: everyone gets the same "random" data
-- 4,000 customers who signed up from January to October 2026 (a few more each month)
INSERT INTO sales_customers
SELECT i,
DATE '2026-01-01' + floor(304 * power(random(), 0.8))::int,
CASE WHEN r < 0.50 THEN 'organic'
WHEN r < 0.80 THEN 'ads'
ELSE 'referral' END
FROM (SELECT i, random() AS r FROM generate_series(1, 4000) AS i) AS s
ORDER BY i;
-- At most one order per customer per month, from the signup month to October 2026.
-- m is the month number since signup; the chance of an order falls as m grows.
INSERT INTO sales_orders (customer_id, order_date, amount, status)
SELECT customer_id, order_date, amount, status
FROM (
SELECT c.id AS customer_id,
GREATEST(c.signup_date,
(date_trunc('month', c.signup_date) + m * interval '1 month')::date
+ floor(random() * 28)::int) AS order_date,
round((15 + random() * 120)::numeric, 2) AS amount,
CASE WHEN random() < 0.05 THEN 'refunded' ELSE 'completed' END AS status,
random() AS r,
CASE WHEN m = 0 THEN 0.70 ELSE 0.40 * power(0.88, m - 1) END
* CASE c.channel WHEN 'referral' THEN 1.25 WHEN 'ads' THEN 0.80 ELSE 1.0 END AS chance
FROM sales_customers AS c
JOIN generate_series(0, 9) AS m ON m <= 10 - extract(month FROM c.signup_date)
ORDER BY c.id, m
) AS x
WHERE r < chance
ORDER BY order_date, customer_id;
-- 8,000 shop sessions in October 2026 and how far each one got
INSERT INTO sales_events
SELECT s.session_id, s.device, e.step, e.event, s.started_at + e.step * interval '2 minutes'
FROM (
SELECT session_id, device, started_at,
CASE WHEN r2 >= CASE device WHEN 'mobile' THEN 0.30 ELSE 0.40 END THEN 1
WHEN r3 >= 0.55 THEN 2
WHEN r4 >= CASE device WHEN 'mobile' THEN 0.60 ELSE 0.75 END THEN 3
ELSE 4 END AS last_step
FROM (
SELECT i AS session_id,
CASE WHEN random() < 0.60 THEN 'mobile' ELSE 'desktop' END AS device,
TIMESTAMP '2026-10-01' + floor(random() * 44640) * interval '1 minute' AS started_at,
random() AS r2, random() AS r3, random() AS r4
FROM generate_series(1, 8000) AS i
) AS raw
) AS s
JOIN (VALUES (1, 'view_product'), (2, 'add_to_cart'), (3, 'checkout'), (4, 'purchase')) AS e (step, event)
ON e.step <= s.last_step
ORDER BY s.session_id, e.step;
ANALYZE sales_customers, sales_orders, sales_events;
DROP TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
setseed
---------
(1 row)
INSERT 0 4000
INSERT 0 7476
INSERT 0 13276
ANALYZE
The first time, three NOTICE lines also say the tables do not exist yet. GREATEST makes sure no order is dated before the signup day. Always check generated data before you analyse it:
SELECT (SELECT COUNT(*) FROM sales_customers) AS customers,
(SELECT COUNT(*) FROM sales_orders) AS orders,
(SELECT COUNT(*) FROM sales_events) AS events,
(SELECT MIN(order_date) FROM sales_orders) AS first_order,
(SELECT MAX(order_date) FROM sales_orders) AS last_order;
SELECT status, COUNT(*) AS orders, SUM(amount) AS amount
FROM sales_orders
GROUP BY status
ORDER BY status;
customers | orders | events | first_order | last_order
-----------+--------+--------+-------------+------------
4000 | 7476 | 13276 | 2026-01-03 | 2026-10-31
(1 row)
status | orders | amount
-----------+--------+-----------
completed | 7136 | 533855.18
refunded | 340 | 27075.25
(2 rows)
If your numbers differ, run the whole script again in one session (we checked them on PostgreSQL 16.15 only).
Monthly revenue
Revenue counts only completed orders. date_trunc('month', ...)::date turns every date into the first day of its month, so GROUP BY 1 makes one row per month (Lesson 10):
SELECT date_trunc('month', order_date)::date AS month,
COUNT(*) AS orders,
SUM(amount) AS revenue,
round(AVG(amount), 2) AS avg_order
FROM sales_orders
WHERE status = 'completed'
GROUP BY 1
ORDER BY 1;
month | orders | revenue | avg_order
------------+--------+----------+-----------
2026-01-01 | 149 | 11243.24 | 75.46
2026-02-01 | 279 | 21383.03 | 76.64
2026-03-01 | 450 | 33162.89 | 73.70
2026-04-01 | 556 | 41590.02 | 74.80
2026-05-01 | 680 | 51135.07 | 75.20
2026-06-01 | 771 | 57170.66 | 74.15
2026-07-01 | 936 | 69392.80 | 74.14
2026-08-01 | 1053 | 80486.07 | 76.44
2026-09-01 | 1066 | 79223.85 | 74.32
2026-10-01 | 1196 | 89067.55 | 74.47
(10 rows)
The average order stays near 75, so revenue grows because there are more orders, not bigger ones.
Month-over-month growth
Month-over-month growth is (this month - last month) / last month * 100. The first CTE (Lesson 21) builds monthly revenue; the second adds last month’s revenue with LAG; the final SELECT does the maths:
WITH monthly AS (
SELECT date_trunc('month', order_date)::date AS month,
SUM(amount) AS revenue
FROM sales_orders
WHERE status = 'completed'
GROUP BY 1
),
with_prev AS (
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly
)
SELECT month, revenue, prev_revenue,
revenue - prev_revenue AS change,
round(100 * (revenue - prev_revenue) / prev_revenue, 1) AS growth_pct
FROM with_prev
ORDER BY month;
month | revenue | prev_revenue | change | growth_pct
------------+----------+--------------+----------+------------
2026-01-01 | 11243.24 | | |
2026-02-01 | 21383.03 | 11243.24 | 10139.79 | 90.2
2026-03-01 | 33162.89 | 21383.03 | 11779.86 | 55.1
2026-04-01 | 41590.02 | 33162.89 | 8427.13 | 25.4
2026-05-01 | 51135.07 | 41590.02 | 9545.05 | 23.0
2026-06-01 | 57170.66 | 51135.07 | 6035.59 | 11.8
2026-07-01 | 69392.80 | 57170.66 | 12222.14 | 21.4
2026-08-01 | 80486.07 | 69392.80 | 11093.27 | 16.0
2026-09-01 | 79223.85 | 80486.07 | -1262.22 | -1.6
2026-10-01 | 89067.55 | 79223.85 | 9843.70 | 12.4
(10 rows)
January has no previous month, so LAG returns NULL and every calculation with it is NULL too (the empty cells; see Lesson 6). In percent, growth mostly slows as the totals get bigger. September is the only month that shrank, by 1.6%. The second CTE names prev_revenue once, so we do not repeat LAG(revenue) OVER (ORDER BY month) in every calculation.
Signup cohorts
A cohort is a group of customers who share a starting point, here the month they signed up. Comparing cohorts shows whether newer customers behave like older ones.
SELECT date_trunc('month', signup_date)::date AS cohort_month,
COUNT(*) AS customers
FROM sales_customers
GROUP BY 1
ORDER BY 1;
cohort_month | customers
--------------+-----------
2026-01-01 | 236
2026-02-01 | 287
2026-03-01 | 370
2026-04-01 | 368
2026-05-01 | 411
2026-06-01 | 418
2026-07-01 | 442
2026-08-01 | 502
2026-09-01 | 480
2026-10-01 | 486
(10 rows)
Next, each order needs a month number: 0 for the signup month, 1 for the next month, and so on. Counting months as year * 12 + month turns this into a subtraction that also works across New Year. EXTRACT comes from Lesson 8. Here is the January cohort:
WITH cohorts AS (
SELECT id AS customer_id,
date_trunc('month', signup_date)::date AS cohort_month,
EXTRACT(YEAR FROM signup_date) * 12 + EXTRACT(MONTH FROM signup_date) AS cohort_index
FROM sales_customers
),
activity AS (
SELECT DISTINCT o.customer_id, c.cohort_month,
EXTRACT(YEAR FROM o.order_date) * 12 + EXTRACT(MONTH FROM o.order_date)
- c.cohort_index AS month_number
FROM sales_orders AS o
JOIN cohorts AS c ON c.customer_id = o.customer_id
WHERE o.status = 'completed'
)
SELECT month_number, COUNT(*) AS active_customers
FROM activity
WHERE cohort_month = '2026-01-01'
GROUP BY month_number
ORDER BY month_number;
month_number | active_customers
--------------+------------------
0 | 149
1 | 83
2 | 73
3 | 78
4 | 57
5 | 48
6 | 49
7 | 46
8 | 34
9 | 24
(10 rows)
DISTINCT counts a customer once per month. Of the 236 January customers, 149 bought in January and 83 in February.
The retention table
A retention table turns those counts into percentages of the cohort, one row per cohort and one column per month number. Two details matter:
- The cohort size comes from
sales_customerswith aLEFT JOIN(Lesson 13), so customers who never ordered still count. - A cohort that signed up in August has only reached month 2 by October.
CASEwithoutELSEreturns NULL (PostgreSQL docs: Conditional Expressions), so those cells stay empty instead of showing a false 0%.
FILTER (Lesson 9) counts the active customers for each month number:
WITH cohorts AS (
SELECT id AS customer_id,
date_trunc('month', signup_date)::date AS cohort_month,
EXTRACT(YEAR FROM signup_date) * 12 + EXTRACT(MONTH FROM signup_date) AS cohort_index
FROM sales_customers
),
activity AS (
SELECT DISTINCT o.customer_id,
EXTRACT(YEAR FROM o.order_date) * 12 + EXTRACT(MONTH FROM o.order_date)
- c.cohort_index AS month_number
FROM sales_orders AS o
JOIN cohorts AS c ON c.customer_id = o.customer_id
WHERE o.status = 'completed'
),
sizes AS (
SELECT cohort_month, COUNT(*) AS customers,
(2026 * 12 + 10) - MIN(cohort_index) AS months_seen -- October 2026 is the last month
FROM cohorts
GROUP BY cohort_month
)
SELECT s.cohort_month, s.customers,
round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 0) / s.customers, 1) AS m0,
CASE WHEN s.months_seen >= 1 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 1) / s.customers, 1) END AS m1,
CASE WHEN s.months_seen >= 2 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 2) / s.customers, 1) END AS m2,
CASE WHEN s.months_seen >= 3 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 3) / s.customers, 1) END AS m3,
CASE WHEN s.months_seen >= 4 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 4) / s.customers, 1) END AS m4,
CASE WHEN s.months_seen >= 5 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 5) / s.customers, 1) END AS m5,
CASE WHEN s.months_seen >= 6 THEN round(100.0 * COUNT(*) FILTER (WHERE a.month_number = 6) / s.customers, 1) END AS m6
FROM sizes AS s
JOIN cohorts AS c ON c.cohort_month = s.cohort_month
LEFT JOIN activity AS a ON a.customer_id = c.customer_id
GROUP BY s.cohort_month, s.customers, s.months_seen
ORDER BY s.cohort_month;
cohort_month | customers | m0 | m1 | m2 | m3 | m4 | m5 | m6
--------------+-----------+------+------+------+------+------+------+------
2026-01-01 | 236 | 63.1 | 35.2 | 30.9 | 33.1 | 24.2 | 20.3 | 20.8
2026-02-01 | 287 | 68.3 | 38.7 | 34.1 | 29.6 | 26.8 | 24.7 | 22.3
2026-03-01 | 370 | 71.9 | 37.8 | 32.7 | 28.1 | 23.8 | 25.1 | 16.2
2026-04-01 | 368 | 65.2 | 39.1 | 34.2 | 31.0 | 25.3 | 18.8 | 22.6
2026-05-01 | 411 | 66.4 | 39.4 | 36.3 | 27.3 | 23.4 | 24.6 |
2026-06-01 | 418 | 60.8 | 40.4 | 34.0 | 28.0 | 25.6 | |
2026-07-01 | 442 | 67.0 | 38.2 | 32.1 | 30.1 | | |
2026-08-01 | 502 | 66.5 | 36.9 | 35.5 | | | |
2026-09-01 | 480 | 66.5 | 33.5 | | | | |
2026-10-01 | 486 | 61.9 | | | | | |
(10 rows)
About two in three customers buy in their signup month (m0). In the next month (m1) only 34% to 40% buy again, and by month 6 about 16% to 23%. The cohorts look alike, so the shop is not getting better or worse at keeping customers. Newer cohorts have had less time, so the empty cells form a triangle.

The value 2026 * 12 + 10 (October 2026) is typed in because this data ends in October. In a live database, compute it from CURRENT_DATE or from MAX(order_date).
The funnel
A funnel counts how many sessions reach each step. FIRST_VALUE gives the number at the first step and LAG the number at the previous step (PostgreSQL docs: Window Functions):
WITH steps AS (
SELECT step, event, COUNT(DISTINCT session_id) AS sessions
FROM sales_events
GROUP BY step, event
)
SELECT step, event, sessions,
round(100.0 * sessions / FIRST_VALUE(sessions) OVER (ORDER BY step), 1) AS pct_of_start,
round(100.0 * sessions / LAG(sessions) OVER (ORDER BY step), 1) AS pct_of_previous
FROM steps
ORDER BY step;
step | event | sessions | pct_of_start | pct_of_previous
------+--------------+----------+--------------+-----------------
1 | view_product | 8000 | 100.0 |
2 | add_to_cart | 2705 | 33.8 | 33.8
3 | checkout | 1520 | 19.0 | 56.2
4 | purchase | 1051 | 13.1 | 69.1
(4 rows)
Out of 8,000 sessions, 1,051 ended with a purchase: a 13.1% conversion rate. The biggest drop is the first one: two in three shoppers leave after viewing a product.
What the numbers tell the owner
Short answers to the four questions:
- Revenue grew every month except September (-1.6%), from 11,243.24 in January to 89,067.55 in October.
- Between 61% and 72% of new customers buy in their signup month, 34% to 40% buy again the next month, and 16% to 23% still buy in month 6.
- Exercise 2 answers the channel question.
- Most shoppers drop out before adding anything to the cart.
Try it yourself
Exercise 1: Revenue so far
Show each month’s revenue and the total revenue up to and including that month.
Exercise 2: Month-1 retention by channel
For customers who signed up from January to September (so they have a month 1), show per channel how many there are, how many placed a completed order in their second month, and that share as a percentage.
Exercise 3: Funnel by device
Show the funnel counts for each device in one row, plus the conversion rate from viewing to purchase.
Solutions
Solution 1
WITH monthly AS (
SELECT date_trunc('month', order_date)::date AS month,
SUM(amount) AS revenue
FROM sales_orders
WHERE status = 'completed'
GROUP BY 1
)
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS revenue_so_far
FROM monthly
ORDER BY month;
month | revenue | revenue_so_far
------------+----------+----------------
2026-01-01 | 11243.24 | 11243.24
2026-02-01 | 21383.03 | 32626.27
2026-03-01 | 33162.89 | 65789.16
2026-04-01 | 41590.02 | 107379.18
2026-05-01 | 51135.07 | 158514.25
2026-06-01 | 57170.66 | 215684.91
2026-07-01 | 69392.80 | 285077.71
2026-08-01 | 80486.07 | 365563.78
2026-09-01 | 79223.85 | 444787.63
2026-10-01 | 89067.55 | 533855.18
(10 rows)
A running total, as in Lesson 26; the last row equals all completed revenue.
Solution 2
WITH customers_m1 AS (
SELECT c.id, c.channel,
EXISTS (
SELECT 1
FROM sales_orders AS o
WHERE o.customer_id = c.id
AND o.status = 'completed'
AND date_trunc('month', o.order_date) = date_trunc('month', c.signup_date) + INTERVAL '1 month'
) AS active_m1
FROM sales_customers AS c
WHERE c.signup_date < '2026-10-01'
)
SELECT channel,
COUNT(*) AS customers,
COUNT(*) FILTER (WHERE active_m1) AS active_in_m1,
round(100.0 * COUNT(*) FILTER (WHERE active_m1) / COUNT(*), 1) AS m1_pct
FROM customers_m1
GROUP BY channel
ORDER BY m1_pct DESC;
channel | customers | active_in_m1 | m1_pct
----------+-----------+--------------+--------
referral | 697 | 332 | 47.6
organic | 1747 | 675 | 38.6
ads | 1070 | 317 | 29.6
(3 rows)
EXISTS (Lesson 20) marks each customer true or false. Referral customers come back most often, ads customers least.
Solution 3
SELECT device,
COUNT(DISTINCT CASE WHEN step = 1 THEN session_id END) AS viewed,
COUNT(DISTINCT CASE WHEN step = 2 THEN session_id END) AS added,
COUNT(DISTINCT CASE WHEN step = 3 THEN session_id END) AS checked_out,
COUNT(DISTINCT CASE WHEN step = 4 THEN session_id END) AS purchased,
round(100.0 * COUNT(DISTINCT CASE WHEN step = 4 THEN session_id END)
/ COUNT(DISTINCT CASE WHEN step = 1 THEN session_id END), 1) AS conversion_pct
FROM sales_events
GROUP BY device
ORDER BY device;
device | viewed | added | checked_out | purchased | conversion_pct
---------+--------+-------+-------------+-----------+----------------
desktop | 3205 | 1273 | 716 | 559 | 17.4
mobile | 4795 | 1432 | 804 | 492 | 10.3
(2 rows)
CASE without ELSE gives NULL for other steps, and COUNT skips NULLs. Mobile shoppers convert far less often.
When you finish, drop the project tables:
DROP TABLE sales_events, sales_orders, sales_customers;
DROP TABLE
Common mistakes
- Integer division.
COUNTreturns integers, and100 * 2705 / 8000gives 33, not 33.8. Write100.0so the division keeps decimals. - Dividing by zero. If last month’s revenue is 0, the growth query fails with
ERROR: division by zero. Wrap the divisor inNULLIF(prev_revenue, 0)to get NULL instead. - Counting cohort size from orders. Joining orders and filtering
WHERE o.status = 'completed'drops customers who never bought (550 of them here), so the January cohort shrinks from 236 to 228 and every percentage looks too high. Count cohort sizes from the customers table. - A window function in WHERE.
WHERE LAG(revenue) OVER (ORDER BY month) IS NOT NULLfails withwindow functions are not allowed in WHERE. Window functions “logically execute after”WHERE(PostgreSQL docs: Window Functions tutorial, Lesson 11), so compute them in a CTE and filter outside. - No ORDER BY or ::date.
GROUP BYdoes not sort: withoutORDER BY, our months came back starting with May, September and March. Without::date,date_truncreturns atimestamp with time zonesuch as2026-01-01 00:00:00+05(+05is our server’s time zone).
Frequently asked questions
What is cohort analysis in SQL?
Cohort analysis groups customers by a shared start, usually the signup or first-order month, and follows each group over time. In SQL you compute each customer’s cohort with date_trunc, give every order a month number, and count active customers per cohort and month number.
How do you calculate customer retention in SQL?
Divide the number of customers from a cohort who were active in month N by the cohort’s size, and multiply by 100. Count the cohort size from the customers table, count each customer once per month with DISTINCT, and use 100.0 so the division keeps decimals.
How do you calculate month-over-month growth in SQL?
Group revenue by month, then use LAG(revenue) OVER (ORDER BY month) to put last month’s value next to this month’s. Growth is 100 * (revenue - prev_revenue) / prev_revenue; use NULLIF if last month can be zero.
Summary
- A SQL sales analytics project combines
date_trunc,GROUP BY, CTEs, window functions andCASEto answer business questions. setseedwithrandom()builds a dataset everyone can reproduce, if the whole script runs in one session.- Month-over-month growth puts each month next to the previous one with
LAG. - A retention table counts active customers per cohort and month number, with cohort sizes from the customers table and
CASEfor months not reached yet. - A funnel counts sessions per step and compares each step with the first and the previous one.
Next lesson
Next: Lesson 39, SQL Project: Design and Build an E-commerce Database.
Sources
- PostgreSQL documentation: Date/Time Functions (date_trunc, EXTRACT)
- PostgreSQL documentation: Window Functions
- PostgreSQL documentation: Window Functions tutorial
- PostgreSQL documentation: WITH Queries (Common Table Expressions)
- PostgreSQL documentation: Conditional Expressions (CASE, NULLIF, GREATEST)
- PostgreSQL documentation: Mathematical Functions (random, setseed)
- PostgreSQL documentation: Set Returning Functions (generate_series)





