This is Module 1 of the Data Analyst to Data Scientist path. Most analysts can write SELECT and GROUP BY. This module covers the three things that separate quick queries from analysis you can trust: joins whose row counts you can reason about, common table expressions (CTEs) that break a query into steps, and window functions for running totals, comparisons and rankings.

You’ll build: a monthly cohort-retention table, in a single query.

You need: Python 3, which includes SQLite, so there is nothing else to install. The same SQL works in PostgreSQL, apart from the date functions noted below.

Setup: a small shop database

Save this as setup.sql. It creates nine customers, their orders over three months, and a table of marketing tags.

CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, signup_date TEXT, country TEXT);
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL);
CREATE TABLE customer_tags (customer_id INTEGER, tag TEXT);

INSERT INTO customers VALUES
  (1, '2026-01-04', 'MX'), (2, '2026-01-09', 'CO'), (3, '2026-01-20', 'MX'), (4, '2026-02-02', 'AR'),
  (5, '2026-02-11', 'CO'), (6, '2026-02-25', 'MX'), (7, '2026-03-03', 'AR'), (8, '2026-03-15', 'CO'),
  (9, '2026-03-28', 'MX');

INSERT INTO orders VALUES
  (101, 1, '2026-01-05', 40), (102, 2, '2026-01-12', 25), (103, 3, '2026-01-22', 60),
  (104, 1, '2026-02-03', 35), (105, 4, '2026-02-04', 50), (106, 5, '2026-02-14', 20),
  (107, 2, '2026-02-20', 30), (108, 6, '2026-02-27', 45), (109, 1, '2026-03-02', 55),
  (110, 4, '2026-03-08', 40), (111, 7, '2026-03-05', 70), (112, 3, '2026-03-18', 25),
  (113, 8, '2026-03-20', 30);

INSERT INTO customer_tags VALUES (1, 'newsletter'), (1, 'referral'), (2, 'newsletter'), (4, 'referral'), (4, 'partner');

Save this as run.py. It loads the data into a throwaway in-memory database and runs whichever query file you give it:

import sqlite3
import sys

con = sqlite3.connect(":memory:")                  # a throwaway database in memory
con.executescript(open("setup.sql").read())        # create and fill the tables
cur = con.execute(open(sys.argv[1]).read())        # run the query file you pass in
print(" | ".join(d[0] for d in cur.description))
for row in cur:
    print(" | ".join("" if v is None else str(v) for v in row))

Run any query with python run.py q1.sql.

1. Joins you can reason about

A LEFT JOIN keeps every row from the left table, even when there is no match. Counting a column from the right table, not *, gives 0 for customers who have never ordered. Save as q1.sql:

-- How many customers have never ordered? A LEFT JOIN keeps customers without a match.
SELECT c.customer_id, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY c.customer_id;
customer_id | orders
1 | 3
2 | 2
3 | 2
4 | 2
5 | 1
6 | 1
7 | 1
8 | 1
9 | 0

Customer 9 signed up but never ordered. With an inner JOIN, they would vanish from the result without warning.

The trap: keys that aren’t unique

Before you join, ask whether the join key is unique on the other side. Customers 1 and 4 each have two tags, so joining orders to tags repeats each of their orders twice. Save as q2.sql:

-- The trap: joining to a table where the key isn't unique multiplies rows.
SELECT
  (SELECT SUM(amount) FROM orders) AS true_revenue,
  (SELECT SUM(o.amount)
     FROM orders o
     LEFT JOIN customer_tags t ON t.customer_id = o.customer_id) AS revenue_after_join;
true_revenue | revenue_after_join
525.0 | 745.0

Revenue is 525, but the join reports 745. Nothing errors and the result looks plausible, which is how wrong numbers reach dashboards unnoticed. Fix it by aggregating the tags to one row per customer before you join, or by not joining tags into a revenue query at all.

2. CTEs: one step at a time

A WITH clause gives a name to an intermediate result. You can read the query top to bottom, and you can check each step by selecting from it on its own. Save as q3.sql:

-- A CTE names each step. Revenue, orders and buyers per month:
WITH monthly AS (
  SELECT strftime('%Y-%m', order_date) AS month, amount, customer_id
  FROM orders
)
SELECT month,
       COUNT(*) AS orders,
       COUNT(DISTINCT customer_id) AS buyers,
       SUM(amount) AS revenue
FROM monthly
GROUP BY month
ORDER BY month;
month | orders | buyers | revenue
2026-01 | 3 | 3 | 125.0
2026-02 | 5 | 5 | 180.0
2026-03 | 5 | 5 | 220.0

strftime('%Y-%m', ...) is SQLite’s way to get the month. In PostgreSQL, use to_char(order_date, 'YYYY-MM') or date_trunc('month', order_date).

3. Window functions: running totals and change

A window function computes across a set of rows related to the current one, without collapsing them as GROUP BY does. Save as q4.sql:

-- Window functions: a running total and month-over-month change, without self-joins.
WITH monthly AS (
  SELECT strftime('%Y-%m', order_date) AS month, SUM(amount) AS revenue
  FROM orders
  GROUP BY month
)
SELECT month,
       revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change_vs_last_month
FROM monthly
ORDER BY month;
month | revenue | running_total | change_vs_last_month
2026-01 | 125.0 | 125.0 | 
2026-02 | 180.0 | 305.0 | 55.0
2026-03 | 220.0 | 525.0 | 40.0

SUM(...) OVER (ORDER BY month) adds up everything up to the current month. LAG(revenue) reads the previous month’s value, so the first month has no change to report. Without window functions, both need a self-join or a subquery.

Ranking within groups

PARTITION BY restarts the window for each group. Here customers are ranked by revenue within each country. Save as q5.sql:

-- Rank customers by revenue within each country.
SELECT c.country, o.customer_id, SUM(o.amount) AS revenue,
       RANK() OVER (PARTITION BY c.country ORDER BY SUM(o.amount) DESC) AS rank_in_country
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.country, o.customer_id
ORDER BY c.country, rank_in_country;
country | customer_id | revenue | rank_in_country
AR | 4 | 90.0 | 1
AR | 7 | 70.0 | 2
CO | 2 | 55.0 | 1
CO | 8 | 30.0 | 2
CO | 5 | 20.0 | 3
MX | 1 | 130.0 | 1
MX | 3 | 85.0 | 2
MX | 6 | 45.0 | 3

Project: a cohort-retention table

A cohort table answers a question every growing business asks: of the customers who first bought in a given month, how many came back one month later, and two months later? Save as q6.sql:

-- Project: monthly cohort retention in one query.
WITH order_months AS (
  SELECT customer_id,
         strftime('%Y-%m', order_date) AS month,
         CAST(strftime('%Y', order_date) AS INTEGER) * 12 + CAST(strftime('%m', order_date) AS INTEGER) AS month_idx
  FROM orders
),
cohorts AS (                       -- each customer's first order month
  SELECT customer_id, MIN(month) AS cohort, MIN(month_idx) AS cohort_idx
  FROM order_months
  GROUP BY customer_id
),
activity AS (                      -- months since the first order, one row per customer and month
  SELECT DISTINCT m.customer_id, c.cohort, c.cohort_idx, m.month_idx - c.cohort_idx AS months_since_first
  FROM order_months m
  JOIN cohorts c ON c.customer_id = m.customer_id
),
last_month AS (SELECT MAX(month_idx) AS idx FROM order_months)
SELECT cohort,
       COUNT(DISTINCT CASE WHEN months_since_first = 0 THEN customer_id END) AS month_0,
       CASE WHEN (SELECT idx FROM last_month) - cohort_idx >= 1
            THEN COUNT(DISTINCT CASE WHEN months_since_first = 1 THEN customer_id END) END AS month_1,
       CASE WHEN (SELECT idx FROM last_month) - cohort_idx >= 2
            THEN COUNT(DISTINCT CASE WHEN months_since_first = 2 THEN customer_id END) END AS month_2
FROM activity
GROUP BY cohort, cohort_idx
ORDER BY cohort;
cohort | month_0 | month_1 | month_2
2026-01 | 3 | 2 | 2
2026-02 | 3 | 1 | 
2026-03 | 2 |  |

Read it row by row. Three customers first ordered in January; two of them ordered again in February, and two in March. The February cohort’s second month, April, is after the last order in the data, so the cell is blank rather than 0. A zero there would wrongly say that nobody came back. Getting that distinction right is exactly the kind of care this path is about.

Project checklist

  • All six queries run and match the outputs above.
  • You can explain why q2 gives 745, and you have fixed it so the join returns 525.
  • Your cohort table shows retention as a percentage of month_0 as well as counts.
  • You’ve run the cohort query on real data from your own work, or on a public dataset.

Next: Module 2, Python and pandas: rebuilding a regular report as a script that runs end to end.

Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.