Suppose you have a customer list and an orders table. Ada has two orders, Ben has one, and Cora has none. A join lets you answer several different questions: which orders belong to each person, who has never ordered, and how much each customer has spent.
Those questions do not all need the same join. This example makes the differences visible with three customers and three orders, small enough to check by hand.
Table of Contents
A database you can start over easily
Use Python 3 with its standard sqlite3 module. Save the three files below in a folder named sql-customer-joins. The runner creates a fresh in-memory database for each run; it neither connects to a website database nor changes an existing file.
Save this setup as schema.sql. Amounts are integer cents to keep the arithmetic in this exercise exact. Foreign keys reject an order pointing to an absent customer, and the check constraint rejects a negative total.
PRAGMA foreign_keys = ON;
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0)
);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cora');
INSERT INTO orders VALUES (101, 1, 1500), (102, 1, 3200), (103, 2, 800);
Six queries, six different questions
Save the following as queries.sql. Read the comments before each query and predict its rows. Notice that every query includes an explicit order, so repeated runs have a predictable presentation.
-- One row per matching order. Ada appears twice.
SELECT c.name, o.id AS order_id, o.total_cents
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
ORDER BY c.id, o.id;
-- Keep customers with no orders too.
SELECT c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
ORDER BY c.id, o.id;
-- Count order IDs, not the placeholder row supplied by LEFT JOIN.
SELECT c.name, COUNT(o.id) AS order_count,
COALESCE(SUM(o.total_cents), 0) AS spent_cents
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;
-- Preserve everyone, but match only orders worth at least 1000 cents.
SELECT c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.total_cents >= 1000
ORDER BY c.id, o.id;
-- Moving the condition to WHERE removes unmatched rows.
SELECT c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.total_cents >= 1000
ORDER BY c.id, o.id;
-- Find customers who have never placed an order.
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.id IS NULL
ORDER BY c.id;
Run the supplied queries
Save this as run.py, then run python3 run.py in the folder. If Python is called py or python on your computer, use that command instead.
from pathlib import Path
import sqlite3
folder = Path(__file__).resolve().parent
with sqlite3.connect(':memory:') as connection:
connection.executescript((folder / 'schema.sql').read_text())
statements = (folder / 'queries.sql').read_text().split(';')
for number, statement in enumerate(statements, start=1):
if not statement.strip():
continue
print(f'Query {number}')
for row in connection.execute(statement):
print(row)
The runner splits this fixed teaching file at semicolons. It is not a general SQL-file parser: semicolons inside text literals, comments, or more complex statements would need different handling. Use SQLite’s own tools or explicit statement strings for a broader runner.
Check the results
| Query | Result to look for |
|---|---|
| 1: INNER JOIN | Ada appears twice, with orders 101 and 102. Ben appears once, with 103. Cora is absent. |
| 2: LEFT JOIN | The same three orders, plus Cora with a missing order ID. Python prints SQL NULL as None. |
| 3: totals | Ada: 2 orders and 4700 cents. Ben: 1 and 800. Cora: 0 and 0. |
| 4: condition in ON | Ada has two qualifying orders. Ben and Cora each remain with a missing order ID. |
| 5: condition in WHERE | Only Ada’s two qualifying orders remain. |
| 6: no orders | Only Cora. |
Repeated customer names are often correct
An order-level result has one row for every match. Ada’s name repeats because she placed two orders. Adding DISTINCT to hide that repetition can lose information about the orders. Decide what one result row means before changing the query.
For a customer-level summary, use grouping and aggregation, as in query 3. Grouping by the customer ID keeps different people with the same name separate. Including the name in the grouping also makes the selected columns clear across SQL systems.
Two LEFT JOIN mistakes to recognize
Counting the wrong thing: LEFT JOIN supplies an unmatched row for Cora. COUNT(*) would count that row as one. COUNT(o.id) counts non-null order IDs, which gives the intended zero orders. COALESCE turns the missing sum into zero for display.
Filtering away unmatched customers: the ON condition controls which orders match. The WHERE condition filters the resulting rows. In query 5, Cora’s missing total does not satisfy the comparison, so she disappears. Place the condition according to the question you are asking, not just where it seems shorter.
Change the sample data
Add an order for Cora, using a new order ID and customer ID 3. Run the file again. Query 6 should now have no rows. Add a fourth customer with no orders and check that the summary includes that person with zeros.
The examples demonstrate query behavior rather than database performance at scale. For a large orders table, examine the query plan and consider an index on orders.customer_id. Indexing decisions depend on the real workload and write cost; three sample orders cannot establish a useful performance benchmark.
Download all the example files
The ZIP contains this original CampCodes example, a README, and an MIT license. No account, package installation, or paid service is needed.
References and verification
SQLite’s SELECT documentation describes joins, grouping, and result filtering. This AI-assisted rewrite was checked on October 22, 2026 using Python 3.13.5 and SQLite. Automated checks compared the exact rows from all six queries and confirmed rejection of an absent customer reference and a negative total. Other database systems may differ in syntax and available functions.
