SQL for data analysis
Overview
You now know enough SQL to answer almost any question about the Bean & Leaf shop. This lesson is about how to do analysis well: turning a vague request (“how are we doing?”) into precise questions, building queries you can trust, and producing numbers people can act on. Along the way it combines techniques from every chapter.
Step 1: define the terms
“Revenue” sounds obvious until you ask: do cancelled orders count? Pending ones? Is shipping included? Do gift cards count as sales? Different answers give different numbers, and most disagreements between reports come from different definitions, not wrong SQL.
For this lesson, the definitions are:
- Orders that count: every status except
cancelled. - Revenue: the sum of
quantity × unit_priceover an order’s items — excluding shipping. - Today: 4 December 2026.
Write definitions down, and build them into your queries in one place — the first CTE.
Step 2: headline KPIs
A KPI (key performance indicator) is a number that summarises how the business is doing. One query can give the headline figures:
WITH valid_orders AS (
SELECT * FROM orders WHERE status <> 'cancelled'
),
order_totals AS (
SELECT o.id, o.customer_id, sum(oi.quantity * oi.unit_price) AS total
FROM valid_orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
GROUP BY o.id, o.customer_id
)
SELECT count(*) AS orders,
count(DISTINCT customer_id) AS customers,
sum(total) AS revenue,
round(avg(total), 2) AS avg_order_value,
round(count(*)::numeric / count(DISTINCT customer_id), 2) AS orders_per_customer
FROM order_totals; orders | customers | revenue | avg_order_value | orders_per_customer
--------+-----------+---------+-----------------+---------------------
22 | 8 | 1146.05 | 52.09 | 2.75
(1 row)Notice the structure: the definition of a valid order lives in the first CTE; the second produces one row per order; the final SELECT summarises. Aggregating at the right level — order totals first, then averages of those — avoids the fan-out trap from Joining many tables.
Step 3: trends over time
Single numbers hide direction. Monthly revenue with a three-month moving average and the change from the previous month:
WITH order_totals AS (
SELECT o.id, o.ordered_at, sum(oi.quantity * oi.unit_price) AS total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.id, o.ordered_at
),
monthly AS (
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) AS orders,
sum(total) AS revenue
FROM order_totals
GROUP BY 1
)
SELECT month, orders, revenue,
round(avg(revenue) OVER (ORDER BY month ROWS 2 PRECEDING), 2) AS moving_avg_3m,
revenue - lag(revenue) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month; month | orders | revenue | moving_avg_3m | change
------------+--------+---------+---------------+--------
2026-01-01 | 3 | 169.50 | 169.50 |
2026-02-01 | 2 | 117.75 | 143.63 | -51.75
2026-03-01 | 3 | 145.65 | 144.30 | 27.90
2026-04-01 | 2 | 100.25 | 121.22 | -45.40
2026-05-01 | 2 | 120.00 | 121.97 | 19.75
2026-06-01 | 1 | 27.25 | 82.50 | -92.75
2026-07-01 | 1 | 77.50 | 74.92 | 50.25
2026-08-01 | 1 | 40.50 | 48.42 | -37.00
2026-09-01 | 2 | 97.40 | 71.80 | 56.90
2026-10-01 | 2 | 147.50 | 95.13 | 50.10
2026-11-01 | 3 | 102.75 | 115.88 | -44.75
(11 rows)The raw monthly numbers jump around; the moving average shows a strong start to the year, a summer dip and a recovery in the autumn. That’s the kind of sentence a report should contain — the query is the evidence behind it.
Step 4: segment customers (RFM)
Not all customers are alike. A classic segmentation, RFM, scores each customer on:
- Recency — how many days since their last order;
- Frequency — how many orders they’ve placed;
- Monetary — how much they’ve spent.
WITH order_totals AS (
SELECT o.id, o.customer_id, o.ordered_at, sum(oi.quantity * oi.unit_price) AS total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.id, o.customer_id, o.ordered_at
),
rfm AS (
SELECT customer_id,
date '2026-12-04' - max(ordered_at)::date AS recency_days,
count(*) AS frequency,
sum(total) AS monetary
FROM order_totals
GROUP BY customer_id
)
SELECT c.first_name, r.recency_days, r.frequency, r.monetary,
CASE
WHEN r.recency_days <= 60 AND r.monetary >= 150 THEN 'champion'
WHEN r.recency_days <= 60 THEN 'active'
WHEN r.monetary >= 120 THEN 'lapsing high-value'
ELSE 'at risk'
END AS segment
FROM rfm AS r
JOIN customers AS c ON c.id = r.customer_id
ORDER BY r.monetary DESC; first_name | recency_days | frequency | monetary | segment
------------+--------------+-----------+----------+--------------------
Ben | 38 | 4 | 285.25 | champion
Asha | 14 | 5 | 217.65 | champion
Grace | 94 | 2 | 136.15 | lapsing high-value
Elena | 149 | 2 | 133.00 | lapsing high-value
Hugo | 62 | 2 | 127.50 | lapsing high-value
Chen | 76 | 3 | 123.75 | lapsing high-value
Farhan | 26 | 2 | 79.00 | active
Dee | 5 | 2 | 43.75 | active
(8 rows)Now marketing has a list to act on: thank the champions, send the lapsing high-value customers an offer before they go quiet for good. The thresholds are business decisions — with more customers you’d usually use ntile(5) to split each measure into quintiles instead of fixed numbers.
And don’t forget the customers who aren’t in this result at all — Isha and Jack signed up but never ordered (a LEFT JOIN or NOT EXISTS from customers finds them). They’re a segment too.
Step 5: cohorts
A cohort is a group of customers who started at the same time. Comparing cohorts shows whether newer customers behave better or worse than older ones. Group customers by the quarter of their first order, and measure how quickly they came back:
WITH valid AS (
SELECT customer_id, ordered_at
FROM orders
WHERE status <> 'cancelled'
),
numbered AS (
SELECT customer_id, ordered_at,
row_number() OVER (PARTITION BY customer_id ORDER BY ordered_at) AS n
FROM valid
),
per_customer AS (
SELECT customer_id,
min(ordered_at) FILTER (WHERE n = 1) AS first_order,
min(ordered_at) FILTER (WHERE n = 2) AS second_order,
count(*) AS orders
FROM numbered
GROUP BY customer_id
)
SELECT to_char(first_order, 'YYYY-"Q"Q') AS cohort,
count(*) AS customers,
round(avg(orders), 1) AS avg_orders,
round(avg(second_order::date - first_order::date)) AS avg_days_to_2nd_order
FROM per_customer
GROUP BY 1
ORDER BY 1; cohort | customers | avg_orders | avg_days_to_2nd_order
---------+-----------+------------+-----------------------
2026-Q1 | 5 | 3.2 | 106
2026-Q2 | 3 | 2.0 | 167
(2 rows)Customers who started in the first quarter have had more time to order again, so they have more orders — always compare cohorts over the same length of time when you can. With years of data, the standard view is a retention table: one row per cohort, one column per month since starting.
Step 6: products bought together
Which products appear in the same orders? A self-join on order_items pairs each line with the other lines of the same order — a.product_id < b.product_id counts each pair once:
SELECT pa.name AS product_a, pb.name AS product_b, count(*) AS orders_together
FROM order_items AS a
JOIN order_items AS b ON b.order_id = a.order_id AND a.product_id < b.product_id
JOIN products AS pa ON pa.id = a.product_id
JOIN products AS pb ON pb.id = b.product_id
GROUP BY pa.name, pb.name
HAVING count(*) >= 2
ORDER BY orders_together DESC, product_a, product_b; product_a | product_b | orders_together
------------------------+-------------------+-----------------
Colombian Supremo | Burr Grinder | 2
Darjeeling First Flush | Assam Breakfast | 2
Ethiopian Yirgacheffe | Assam Breakfast | 2
Ethiopian Yirgacheffe | Pour-Over Dripper | 2
(4 rows)Grinders sell with Colombian beans, drippers with Ethiopian — ideas for bundles and “customers also bought” suggestions. This is market basket analysis in its simplest form.
Step 7: check before you share
Every analysis deserves a few sanity checks:
SELECT (SELECT sum(quantity * unit_price) FROM order_items AS oi
JOIN orders AS o ON o.id = oi.order_id
WHERE o.status <> 'cancelled') AS revenue_direct,
(SELECT count(*) FROM orders WHERE status <> 'cancelled') AS valid_orders,
(SELECT count(*) FROM orders AS o
WHERE NOT EXISTS (SELECT 1 FROM order_items WHERE order_id = o.id)) AS orders_without_items; revenue_direct | valid_orders | orders_without_items
----------------+--------------+----------------------
1146.05 | 22 | 0
(1 row)The direct revenue total matches the KPI query (1,146.05), the order count matches, and no order is missing its items. Other good checks: do counts change unexpectedly when you add a join? Are there NULLs in columns you group by? Do the monthly figures add up to the total?
Step 8: share it
Turn the queries people will reuse into views (Views), schedule heavy ones as materialized views, export one-off results with \copy … TO 'file.csv' (Importing and exporting data), or connect a BI tool such as Metabase, Power BI or Looker Studio directly to the database. And always say which definitions you used.
Tip: keep your analysis queries in files, with a comment at the top stating the question, the definitions and the date. Six months later, when someone asks “where did this number come from?”, you’ll be able to answer — and re-run it.
A KPI table by country
Management wants key figures per country. Ignoring cancelled orders, return for each customer country: customers (how many different customers ordered), orders (how many orders), revenue (total of quantity × unit price) and avg_order_value (revenue divided by orders, rounded to 2 decimal places). Build it with CTEs: first one row per order with its items total, then aggregate by country. Sort by revenue, highest first.
WITH order_totals AS (
SELECT o.id, o.customer_id,
sum(oi.quantity * oi.unit_price) AS total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.id, o.customer_id
)
SELECT * FROM order_totals;WITH order_totals AS (
SELECT o.id, o.customer_id,
sum(oi.quantity * oi.unit_price) AS total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.id, o.customer_id
)
SELECT c.country,
count(DISTINCT t.customer_id) AS customers,
count(*) AS orders,
sum(t.total) AS revenue,
round(sum(t.total) / count(*), 2) AS avg_order_value
FROM order_totals AS t
JOIN customers AS c ON c.id = t.customer_id
GROUP BY c.country
ORDER BY revenue DESC;Summary
- Start every analysis with a precise question and definitions: which orders count, which date range, what exactly 'revenue' means.
- Build analyses as CTE pipelines — clean rows, then per-entity totals, then summaries — so each step can be checked.
- Window functions give trends (running totals, growth), and CASE or ntile turns measures into segments.
- Cohort analysis groups customers by when they started; self-joins on order lines find products bought together.
- Before sharing, reconcile totals with simple queries and look for NULLs, duplicates and fan-out.