data science / sql
Learn SQL Free: JOIN and GROUP BY on a Four-Customer Table
Most SQL tutorials show you the syntax and stop. This one runs a JOIN and a GROUP BY on a table small enough to check by hand, shows the exact rows each query returns, and points out the three places where rows quietly disappear. Then it lists the free practice sites worth your time.
JOIN and GROUP BY are the two ideas that separate "I can SELECT from one table" from "I can answer a business question." They are also the two where wrong answers look right: the query runs, a table of plausible numbers comes back, and nothing warns you that a customer is missing or a total is short. The fastest way to learn them is to work on data tiny enough that you already know the correct answer. Everything below uses two tables and nine rows, and I ran each query in SQLite 3 through Python's built-in sqlite3 module to get the results shown.
01 · THE DATA
Two tables you can hold in your head
A shop has four customers and five orders. One customer, Dev, has never ordered. One order, number 5, has no total recorded yet. Both facts matter later.
| customers.id | name | country |
|---|---|---|
| 1 | Ana | PT |
| 2 | Ben | US |
| 3 | Chi | US |
| 4 | Dev | IN |
| orders.id | customer_id | total | status |
|---|---|---|---|
| 1 | 1 | 40 | paid |
| 2 | 1 | 25 | paid |
| 3 | 2 | 90 | paid |
| 4 | 2 | 10 | refunded |
| 5 | 3 | NULL | paid |
orders.customer_id points at customers.id. That pointer is a foreign key, and it is what a JOIN follows. Before you write any query, say the answer out loud: Ana ordered twice for 65 in total, Ben twice for 100, Chi once with an unknown total, and Dev never.
02 · JOIN, THEN GROUP
What JOIN and GROUP BY each produce
Take the question "how many orders and how much money per customer?" Think of the database doing it in two passes. The JOIN first pairs every order with its customer, giving one row per order. GROUP BY then folds those rows into one row per customer.
SELECT c.name, COUNT(*) AS orders, SUM(o.total) AS spent FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY c.name ORDER BY spent DESC;
| name | orders | spent |
|---|---|---|
| Ben | 2 | 100.0 |
| Ana | 2 | 65.0 |
| Chi | 1 | NULL |
Check it against the answer you wrote down. Ben and Ana are right. Chi shows one order and a NULL total, which is honest: the total is unknown. But Dev is gone. An inner JOIN keeps only rows that match on both sides, so a customer with no orders never enters the result. If the question had been "which customers have not ordered?", this query could not answer it.
SUM(o.total). Adding HAVING SUM(o.total) > 50 after grouping by country returns PT with 65 and US with 100, and drops IN. Reading a query in the order the database runs it (FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY) explains most "why is this an error" moments.03 · WHERE ROWS GO MISSING
LEFT JOIN, NULL and the filter that undoes your join
To keep Dev, switch to a LEFT JOIN, which keeps every row from the left table and fills the right side with NULL when nothing matches. Now the choice of counting function matters:
SELECT c.name,
COUNT(*) AS row_count,
COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY c.name;| name | row_count | orders |
|---|---|---|
| Ana | 2 | 2 |
| Ben | 2 | 2 |
| Chi | 1 | 1 |
| Dev | 1 | 0 |
Dev is back, but COUNT(*) says Dev has one order. The LEFT JOIN produced one placeholder row full of NULLs, and COUNT(*) counts rows. COUNT(o.id) counts non-NULL values, so it correctly says zero. That is the first trap: count a column from the right-hand table, not the star.
The second trap is a filter that quietly turns a LEFT JOIN back into an inner join. Say you only want paid orders:
| Filter written as | Rows returned | Dev present? |
|---|---|---|
LEFT JOIN ... ON ... AND o.status = 'paid' | Ana 2, Ben 1, Chi 1, Dev 0 | Yes |
LEFT JOIN ... ON ... WHERE o.status = 'paid' | Ana 2, Ben 1, Chi 1 | No |
Dev's placeholder row has status = NULL, and NULL = 'paid' is not true, so WHERE discards it. Putting the condition in the ON clause filters the right-hand table before the join and keeps the left side intact.
ORDER BY spent DESC. PostgreSQL treats NULL as larger than any value, so the same query lists it first unless you add NULLS LAST. SUM also skips NULLs silently: Chi's order exists, but contributes nothing to the total.04 · FREE PRACTICE
Free places to write real queries
Reading about JOINs does little. Use the sites below to write several dozen queries, and rebuild the tables above yourself in whichever one you pick. SQLBolt is the fastest start because lessons 6 and 10 cover exactly the JOIN and aggregate material on this page.
- SQLBolt Lesson 6: multi-table queries with JOINs ↗Interactive lesson in the browser that explains INNER JOIN and then moves on to the outer joins, with exercises after each. SQLBolt describes its lessons as running right in your browser.sqlbolt.com
- SQLBolt Lesson 10: queries with aggregates ↗COUNT, SUM, AVG and GROUP BY with exercises, the companion to the JOIN lesson.sqlbolt.com
- Select Star SQL ↗An interactive book on a real dataset. Its author states it is free of charge, free of ads and needs no registration or downloads; each chapter is meant to take about 30 minutes.selectstarsql.com
- ThoughtSpot SQL Tutorial (formerly the Mode tutorial) ↗The old mode.com/sql-tutorial address now redirects here. Written lessons grouped as basic, intermediate and advanced SQL for data analysis, including a GROUP BY lesson and a joins lesson.thoughtspot.com
- SQLZoo ↗Graded exercises you run against MySQL, PostgreSQL, SQL Server or Oracle, so you can see where the dialects differ.sqlzoo.net
- The SQL Murder Mystery ↗A murder case you solve by querying a database from Knight Lab. Good for a second pass once SELECT and JOIN feel familiar.mystery.knightlab.com
- PostgreSQL Exercises ↗A series of questions on one simple dataset, written to sit beside a book or the Postgres documentation.pgexercises.com
- CS50's Introduction to Databases with SQL ↗Harvard's seven-week course on OpenCourseWare: lectures and problem sets, starting with SQLite and ending with an introduction to PostgreSQL and MySQL. The free route has no certificate; the verified one goes through edX.cs50.harvard.edu
- Kaggle Learn: Intro to SQL ↗A roughly three-hour micro-course on Google BigQuery. Kaggle states that its courses cost nothing and lists a certificate; the catch is that BigQuery's dialect differs a little from SQLite and Postgres.kaggle.com
05 · WHAT TO INSTALL
Do you need a database on your machine?
Not at first. The browser sites above cover your first few weeks. When you want your own data, pick by what you are trying to do:
| You want to | Use | Why |
|---|---|---|
| Try queries inside a Python script or notebook | SQLite via import sqlite3 | The module ships with Python, so there is nothing to install or configure. This is what produced the results above. |
| Practice the database most employers run | PostgreSQL | Installers for every major OS, and its tutorial chapters on joins and aggregates are a clear second explanation. |
| Query CSV files without loading a server | DuckDB | Its site describes it as an analytical SQL database that can run in-process, and it reads CSV, JSON and Parquet files. |
The core of SELECT, JOIN, GROUP BY and HAVING is shared across all of these. The differences show up in date functions, string functions and NULL ordering, which is why one dialect-specific habit is worth learning early: read the documentation page for the database in front of you.
06 · FAQ
Frequently asked questions
What is the difference between INNER JOIN and LEFT JOIN?
An INNER JOIN keeps only rows that have a match on both sides, so a customer with no orders disappears from the result. A LEFT JOIN keeps every row from the left table and fills the right-hand columns with NULL when there is no match, which is how you find customers who have never ordered.
Why does COUNT(*) show 1 for a customer with no orders?
After a LEFT JOIN, a customer without orders still produces one row, filled with NULLs. COUNT(*) counts rows, so it returns 1. COUNT(o.id) counts only non-NULL values from the orders table, so it returns 0, which is the answer you want.
Why did my LEFT JOIN drop rows after I added a WHERE filter?
Unmatched rows carry NULL in every right-hand column, and a condition such as o.status = 'paid' is not true for NULL, so WHERE removes them. Move the condition into the ON clause to filter the right table before the join and keep the unmatched left rows.
Do I need to install a database to learn SQL?
No. SQLBolt, Select Star SQL and SQLZoo run in the browser. When you want a local one, Python's built-in sqlite3 module needs no installation, and PostgreSQL is the usual next step.