SQL for Analytics — Free Starter Lesson
Free Software starter lesson · 15 minutes · Beginner. Use any SQL editor that supports common table expressions, such as SQLite. You’ll learn to check whether a join changes the number of rows or the total in a report.
Watch the SQL Analytics video.
Build a baseline
This example has one row per order. The baseline should show three orders and €100 in revenue.
WITH orders(order_id, customer_id, amount) AS (
VALUES (1, 'A', 25), (2, 'A', 35), (3, 'B', 40)
)
SELECT COUNT(*) AS row_count, SUM(amount) AS revenue
FROM orders;
Check the join
The customer list has two rows for A. Predict what happens to A’s two orders, then run the query and compare it with your baseline.
WITH orders(order_id, customer_id, amount) AS (
VALUES (1, 'A', 25), (2, 'A', 35), (3, 'B', 40)
), customers(customer_id, segment) AS (
VALUES ('A', 'Local'), ('A', 'Local'), ('B', 'Regional')
)
SELECT COUNT(*) AS row_count, SUM(o.amount) AS revenue
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id;
Try it yourself
Keep the two common table expressions and replace the final query with SELECT customer_id, COUNT(*) FROM customers GROUP BY customer_id HAVING COUNT(*) > 1; to locate duplicate keys. Remove the duplicate A row from the sample, then rerun the join. In a real dataset, confirm which record should be retained with the data owner before removing anything.
Self-check: The original join returns five rows and €160 because A’s €60 is counted twice. The corrected join returns three rows and €100. Explain why using DISTINCT on the amount would be unreliable when two different orders have the same value.
Open Learning Progress to mark this lesson complete or resume later.