Lab: Retention, Running Totals and Gaps-and-Islands
On a small shop database in PostgreSQL 17, compute month-over-month revenue growth, per-customer running totals, a 7-day moving average over a calendar, a monthly cohort retention table and login streaks with the gaps-and-islands pattern.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start PostgreSQL and load the data
- Step 2: Monthly revenue and month-over-month growth
- Step 3: Running totals and each customer's first and latest order
- Step 4: A 7-day moving average of sign-ups
- Step 5: Monthly cohort retention
- Step 6: Login streaks with gaps-and-islands
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced SQL
- Window Functions: Partitions, Order and Frames Concept · 25 min
- Lab: Retention, Running Totals and Gaps-and-Islands Lab · 30 min
- Readable Step-by-Step Queries with CTEs and Recursion Worked example · 25 min
- Multi-Level Reports, Pivots and Result-Set Comparisons Lab · 25 min
- Deduplicate, MERGE and Package the Load as a Procedure Lab · 30 min
- Check: Analytical Query Challenge Knowledge check · 8 questions
What you will learn
- Compute rankings, running totals, period-over-period changes and moving averages with window functions and explicit frames.
Prerequisites: SQL Fundamentals
01. Goal and setup
In this lab you answer five questions that product and finance teams ask every month, each with one window-function query: revenue growth, spend so far per customer, the sign-up trend, retention after the first month, and login streaks. The data is small enough to check every answer by hand, and you should be able to explain each number.
You need Docker and about 500 MB of disk; the lab was tested with postgres:17-alpine (PostgreSQL 17.11). It builds on Window Functions: Partitions, Order and Frames, so read that first if PARTITION BY or frames are new to you. Create a folder window-lab/ and save each SQL file there as you go.
window-lab/
├── seed.sql step 1: customers, orders and logins
├── growth.sql step 2: monthly revenue and growth
├── running.sql step 3: running totals, first and latest order
├── moving.sql step 4: 7-day moving average of sign-ups
├── retention.sql step 5: cohort retention table
└── streaks.sql step 6: login streaks02. Step 1: Start PostgreSQL and load the data
Start a PostgreSQL 17 container. If sql-lab already exists from an earlier lesson, run docker start sql-lab instead.
docker run --name sql-lab -e POSTGRES_PASSWORD=learnsql -d postgres:17-alpineThe seed script creates three tables. customers gets its rows from generate_series: the expression (day * 7) % 4 gives 3, 2, 1 and 0 sign-ups in turn, so every fourth day has no sign-up and therefore no row. orders holds 15 orders from six customers between January and April 2026; customer 4 placed two orders on the same day. logins holds daily logins for two users, and user 2 has a duplicate row for 2 March, as real event logs often do.
CREATE TABLE customers (
customer_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
signed_up date NOT NULL
);
-- 3, 2, 1, 0, 3, 2, 1, 0 ... sign-ups per day: every fourth day has none
INSERT INTO customers (signed_up)
SELECT d::date
FROM generate_series(date '2026-01-01', date '2026-01-21', interval '1 day') AS d,
generate_series(1, (extract(day FROM d)::int * 7) % 4) AS n
ORDER BY d;
CREATE TABLE orders (
order_id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers,
order_date date NOT NULL,
amount numeric(8,2) NOT NULL
);
INSERT INTO orders VALUES
( 1, 1, '2026-01-05', 40), ( 2, 2, '2026-01-09', 60), ( 3, 2, '2026-01-20', 15),
( 4, 3, '2026-01-28', 35), ( 5, 4, '2026-02-02', 50), ( 6, 4, '2026-02-02', 10),
( 7, 1, '2026-02-10', 25), ( 8, 5, '2026-02-14', 80), ( 9, 1, '2026-03-03', 30),
(10, 4, '2026-03-08', 20), (11, 2, '2026-03-15', 45), (12, 6, '2026-03-21', 55),
(13, 5, '2026-04-01', 30), (14, 1, '2026-04-12', 20), (15, 6, '2026-04-18', 25);
CREATE TABLE logins (
user_id int NOT NULL,
login_date date NOT NULL
);
INSERT INTO logins VALUES
(1, '2026-03-01'), (1, '2026-03-02'), (1, '2026-03-03'), (1, '2026-03-06'),
(1, '2026-03-07'), (1, '2026-03-10'),
(2, '2026-03-01'), (2, '2026-03-02'), (2, '2026-03-02'), (2, '2026-03-04'),
(2, '2026-03-05'), (2, '2026-03-06'), (2, '2026-03-07');
SELECT 'customers' AS table_name, count(*) AS row_count FROM customers
UNION ALL SELECT 'orders', count(*) FROM orders
UNION ALL SELECT 'logins', count(*) FROM logins;docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
-c "DROP DATABASE IF EXISTS shop" -c "CREATE DATABASE shop"
docker exec -i sql-lab psql -U postgres -d shop -X -q < seed.sql table_name | row_count
------------+-----------
customers | 33
orders | 15
logins | 13
(3 rows)Every later step runs the same way: save the file, then pipe it into psql. Running the step 1 commands again resets the database.
03. Step 2: Monthly revenue and month-over-month growth
Growth compares each month with the one before it, so you need the previous row: that is lag. Window functions run after GROUP BY, so the cleanest shape is two steps. The CTE monthly collapses orders to one row per month with date_trunc('month', ...), which rounds a date down to the first of its month. The outer query then reads the previous month with lag(revenue) OVER (ORDER BY month).
WITH monthly AS (
SELECT date_trunc('month', order_date)::date AS month,
sum(amount) AS revenue
FROM orders
GROUP BY 1
)
SELECT month, revenue,
lag(revenue) OVER (ORDER BY month) AS prev_revenue,
round(100 * (revenue - lag(revenue) OVER (ORDER BY month))
/ lag(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;docker exec -i sql-lab psql -U postgres -d shop -X -q < growth.sql month | revenue | prev_revenue | growth_pct
------------+---------+--------------+------------
2026-01-01 | 150.00 | |
2026-02-01 | 165.00 | 150.00 | 10.0
2026-03-01 | 150.00 | 165.00 | -9.1
2026-04-01 | 75.00 | 150.00 | -50.0
(4 rows)Check February by hand: 25 + 50 + 10 + 80 = 165, and (165 − 150) / 150 = 10 %. January has no previous month, so its growth is NULL rather than 0 %, which would claim that revenue was flat. This query assumes every month has orders. If a month could be empty, build a calendar of months first, as step 4 does for days, or lag will compare April with February.
04. Step 3: Running totals and each customer's first and latest order
A running total adds each row to the sum of the rows before it. With PARTITION BY customer_id it restarts for every customer. The first query computes it twice: once with the default frame and once with an explicit ROWS frame and order_id as a tie-breaker. Look at customer 4, whose orders 5 and 6 share a date. The second query uses a frame over the whole partition to put each customer's first and latest order on every row; DISTINCT then keeps one copy per customer.
SELECT customer_id, order_id, order_date, amount,
sum(amount) OVER (PARTITION BY customer_id ORDER BY order_date)
AS default_frame,
sum(amount) OVER (PARTITION BY customer_id ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS running_total
FROM orders
WHERE customer_id IN (1, 4)
ORDER BY customer_id, order_date, order_id;
SELECT DISTINCT customer_id,
first_value(order_date) OVER w AS first_order,
last_value(order_date) OVER w AS latest_order,
count(*) OVER w AS orders
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY customer_id;docker exec -i sql-lab psql -U postgres -d shop -X -q < running.sql customer_id | order_id | order_date | amount | default_frame | running_total
-------------+----------+------------+--------+---------------+---------------
1 | 1 | 2026-01-05 | 40.00 | 40.00 | 40.00
1 | 7 | 2026-02-10 | 25.00 | 65.00 | 65.00
1 | 9 | 2026-03-03 | 30.00 | 95.00 | 95.00
1 | 14 | 2026-04-12 | 20.00 | 115.00 | 115.00
4 | 5 | 2026-02-02 | 50.00 | 60.00 | 50.00
4 | 6 | 2026-02-02 | 10.00 | 60.00 | 60.00
4 | 10 | 2026-03-08 | 20.00 | 80.00 | 80.00
(7 rows)
customer_id | first_order | latest_order | orders
-------------+-------------+--------------+--------
1 | 2026-01-05 | 2026-04-12 | 4
2 | 2026-01-09 | 2026-03-15 | 3
3 | 2026-01-28 | 2026-01-28 | 1
4 | 2026-02-02 | 2026-03-08 | 3
5 | 2026-02-14 | 2026-04-01 | 2
6 | 2026-03-21 | 2026-04-18 | 2
(6 rows)For customer 1 the two columns agree. For customer 4 the default frame shows 60 on both 2 February orders, because RANGE treats rows with the same date as peers and adds them together. The ROWS frame shows 50 and then 60. A statement of account wants the second behaviour. Here, WHERE customer_id IN (1, 4) is safe because it removes whole partitions. A filter that removes rows inside a partition, such as a date filter, would change the totals, which step 4 shows.
05. Step 4: A 7-day moving average of sign-ups
A moving average smooths daily noise by averaging each day with the days before it. The file holds two queries. The first counts sign-ups per day straight from customers, so days without sign-ups have no row. The second left-joins a calendar of every day in January to the customers, so empty days become rows with 0. Both use ROWS BETWEEN 6 PRECEDING AND CURRENT ROW and show only the days from 12 January. That filter sits in the outer query, after the window has been computed, so earlier days still feed the average.
-- 1. no calendar: days without sign-ups are missing
WITH daily AS (
SELECT signed_up AS day, count(*) AS signups
FROM customers GROUP BY signed_up
), moving AS (
SELECT day, signups,
round(avg(signups) OVER (ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS avg_7_rows
FROM daily
)
SELECT * FROM moving WHERE day >= date '2026-01-12' ORDER BY day;
-- 2. with a calendar: every day has a row
WITH calendar AS (
SELECT d::date AS day
FROM generate_series(date '2026-01-01', date '2026-01-21', interval '1 day') AS d
), daily AS (
SELECT c.day, count(cu.customer_id) AS signups
FROM calendar c
LEFT JOIN customers cu ON cu.signed_up = c.day
GROUP BY c.day
), moving AS (
SELECT day, signups,
round(avg(signups) OVER (ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS avg_7_days
FROM daily
)
SELECT * FROM moving WHERE day >= date '2026-01-12' ORDER BY day;docker exec -i sql-lab psql -U postgres -d shop -X -q < moving.sql day | signups | avg_7_rows
------------+---------+------------
2026-01-13 | 3 | 2.14
2026-01-14 | 2 | 2.00
2026-01-15 | 1 | 1.86
2026-01-17 | 3 | 2.14
2026-01-18 | 2 | 2.00
2026-01-19 | 1 | 1.86
2026-01-21 | 3 | 2.14
(7 rows)
day | signups | avg_7_days
------------+---------+------------
2026-01-12 | 0 | 1.29
2026-01-13 | 3 | 1.43
2026-01-14 | 2 | 1.57
2026-01-15 | 1 | 1.71
2026-01-16 | 0 | 1.29
2026-01-17 | 3 | 1.43
2026-01-18 | 2 | 1.57
2026-01-19 | 1 | 1.71
2026-01-20 | 0 | 1.29
2026-01-21 | 3 | 1.43
(10 rows)The first result skips 12, 16 and 20 January, and its averages are too high: on 13 January the seven rows reach back to 5 January, nine calendar days, and the zero days are not in the average at all. The second result has a row for every day. On every row shown, its window holds seven days, and the true 7-day average on 13 January is (1 + 0 + 3 + 2 + 1 + 0 + 3) / 7 = 1.43. Note count(cu.customer_id) rather than count(*): after a left join, an empty day still has one row with NULL customer columns, and count(*) would count it as one sign-up.
06. Step 5: Monthly cohort retention
A cohort is a group of customers who started in the same period. Here a customer's cohort is the month of their first order. Retention asks how many of a cohort ordered again 1, 2 or 3 months later. The query has three parts. firsts finds each customer's cohort month. activity turns every order into a month number, 0 for the cohort month itself, and DISTINCT keeps one row per customer per month, so two orders in one month count once. The final SELECT pivots month numbers into columns with count(*) FILTER (WHERE ...), which counts only the rows that pass the condition.
The month number is computed from year and month parts, (year difference) × 12 + (month difference), because extract(month FROM age(a, b)) returns only the month field of the interval and wraps around after 12.
WITH firsts AS (
SELECT customer_id,
date_trunc('month', min(order_date))::date AS cohort_month
FROM orders GROUP BY customer_id
), activity AS (
SELECT DISTINCT o.customer_id, f.cohort_month,
(extract(year FROM o.order_date) - extract(year FROM f.cohort_month)) * 12
+ extract(month FROM o.order_date) - extract(month FROM f.cohort_month)
AS month_number
FROM orders o JOIN firsts f USING (customer_id)
)
SELECT cohort_month,
count(*) FILTER (WHERE month_number = 0) AS m0,
count(*) FILTER (WHERE month_number = 1) AS m1,
count(*) FILTER (WHERE month_number = 2) AS m2,
count(*) FILTER (WHERE month_number = 3) AS m3
FROM activity
GROUP BY cohort_month
ORDER BY cohort_month;docker exec -i sql-lab psql -U postgres -d shop -X -q < retention.sql cohort_month | m0 | m1 | m2 | m3
--------------+----+----+----+----
2026-01-01 | 3 | 1 | 2 | 1
2026-02-01 | 2 | 1 | 1 | 0
2026-03-01 | 1 | 1 | 0 | 0
(3 rows)Read the January row: customers 1, 2 and 3 started; in February only customer 1 came back, in March customers 1 and 2, in April customer 1. Retention can rise, because a customer can skip a month and return. Zeros on the right of later cohorts partly mean "no data yet": the data ends in April.
07. Step 6: Login streaks with gaps-and-islands
An island is a run of consecutive days; a gap is a break between runs. The classic trick numbers each user's login days with row_number() and subtracts that number from the date. While the dates advance one day at a time, the date and the row number grow together, so their difference stays the same. After a gap, the date jumps ahead but the number does not, so the difference changes. Grouping by that difference puts each streak in one group.
The trick needs exactly one row per user per day. The days CTE removes the duplicate 2 March login first. Without it, the extra row advances the row number but not the date, and the streak breaks in the wrong place.
WITH days AS (
SELECT DISTINCT user_id, login_date FROM logins
), grouped AS (
SELECT user_id, login_date,
login_date - row_number() OVER (PARTITION BY user_id
ORDER BY login_date)::int AS island
FROM days
)
SELECT user_id, min(login_date) AS streak_start, max(login_date) AS streak_end,
count(*) AS days
FROM grouped
GROUP BY user_id, island
ORDER BY user_id, streak_start;docker exec -i sql-lab psql -U postgres -d shop -X -q < streaks.sql user_id | streak_start | streak_end | days
---------+--------------+------------+------
1 | 2026-03-01 | 2026-03-03 | 3
1 | 2026-03-06 | 2026-03-07 | 2
1 | 2026-03-10 | 2026-03-10 | 1
2 | 2026-03-01 | 2026-03-02 | 2
2 | 2026-03-04 | 2026-03-07 | 4
(5 rows)Now run the same file with DISTINCT removed.
sed 's/SELECT DISTINCT user_id/SELECT user_id/' streaks.sql \
| docker exec -i sql-lab psql -U postgres -d shop -X -q user_id | streak_start | streak_end | days
---------+--------------+------------+------
1 | 2026-03-01 | 2026-03-03 | 3
1 | 2026-03-06 | 2026-03-07 | 2
1 | 2026-03-10 | 2026-03-10 | 1
2 | 2026-03-01 | 2026-03-07 | 6
2 | 2026-03-02 | 2026-03-02 | 1
(5 rows)User 2 now has a six-day streak from 1 to 7 March, although 3 March is missing, plus a one-day streak on 2 March. The duplicate row shifted every later difference by one day, and by chance the shifted values joined the next island. When the input is a state that changes, such as "online" and "offline", use the second classic form: mark each row where the state differs from lag(state) with 1, and take a running sum of those marks as the island number.
08. Check your understanding
09. Apply it
The practice project asks for monthly revenue with growth, each customer's first and latest order and a 7-day moving average of sign-ups, with tests that compare outputs to expected results. Extend this lab towards it:
- Turn the retention counts into percentages of
m0, rounded to one decimal, and add a column for the cohort size. - Change step 2 so that it still works when a month has no orders: generate the months with
generate_seriesand left-join the revenue. - Return only each user's longest streak, using
row_number()over the streaks ordered by length and then start date. - For each query, write the expected rows as a
VALUESlist. Lesson 4 shows how to compare a result with them usingEXCEPT.
10. Review prompt
Without looking back, explain in your own words:
- why growth is computed in two steps, a grouped CTE and then
lagin the outer query; - why the running total of customer 4 differs between the default frame and the
ROWSframe; - what a calendar table fixes in a moving average, and why
count(column)matters after the left join; - why
date - row_number()stays constant inside a streak, and what one duplicate row does to it.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.