
Often the most important row in a report belongs to the customer who has placed no orders. An inner join discards that customer, a left join can keep them, and a later filter can discard them again. Three customers and two orders are enough to show this behavior.
Run a complete fixture
Save the example as joins.py, then run python joins.py with Python 3.11+ and its built-in SQLite module. The SQL lives in Python strings, so you need neither a separate database server nor a command-line client.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER, cents INTEGER);
INSERT INTO customers VALUES (1,'Maple'),(2,'Cedar'),(3,'Pine');
INSERT INTO orders VALUES (10,1,1200),(11,1,800);
""")
all_orders = db.execute("""
SELECT c.id, COUNT(o.id)
FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id ORDER BY c.id
""").fetchall()
large_orders = db.execute("""
SELECT c.id, COUNT(o.id)
FROM customers AS c LEFT JOIN orders AS o
ON o.customer_id = c.id AND o.cents >= 1000
GROUP BY c.id ORDER BY c.id
""").fetchall()
assert all_orders == [(1, 2), (2, 0), (3, 0)]
assert large_orders == [(1, 1), (2, 0), (3, 0)]
print(all_orders)
print(large_orders)
db.close()
Count matches, not output rows
Consider the first result, [(1, 2), (2, 0), (3, 0)]. Customer 1 (Maple) placed two orders, for 1200 and 800 cents. Customers 2 (Cedar) and 3 (Pine) have placed none but still show up, because they are on the preserved left side of customers AS c LEFT JOIN orders AS o.
Use COUNT(o.id) rather than COUNT(*) to count matches. Before GROUP BY, the LEFT JOIN produces four rows: customer 1 has two matches, while customer 2 has a null-padded row (o.id = NULL, o.cents = NULL), as does customer 3 (o.id = NULL, o.cents = NULL). Because COUNT(*) counts rows even when joined values are null, COUNT(*) would show 1 order for customer 2 and 1 for customer 3. By ignoring null keys, COUNT(o.id) returns 0 actual matches.
Scroll sideways if the columns extend beyond the frame.
| Join and filter pattern | Result on the fixture (Maple=1, Cedar=2, Pine=3) |
Why it produces this output |
|---|---|---|
INNER JOIN orders AS o ON o.customer_id = c.id |
[(1, 2)] |
Drops customers 2 and 3 entirely because they have no matching row in orders |
LEFT JOIN orders AS o ON o.customer_id = c.id with COUNT(o.id) |
[(1, 2), (2, 0), (3, 0)] |
Preserves all three customers and counts only non-null matched o.id values |
LEFT JOIN orders AS o ON o.customer_id = c.id with COUNT(*) |
[(1, 2), (2, 1), (3, 1)] |
Bug: counts the null-padded left-join row itself as if it were an order |
LEFT JOIN orders AS o ON o.customer_id = c.id AND o.cents >= 1000 |
[(1, 1), (2, 0), (3, 0)] |
Filters which orders can match during the join, while still preserving unmatched customers with 0 |
LEFT JOIN orders AS o ON o.customer_id = c.id WHERE o.cents >= 1000 |
[(1, 1)] |
WHERE runs after the join; NULL >= 1000 is unknown, so customers 2 and 3 are eliminated |
Put the condition in the right place
The second query moves o.cents >= 1000 into the ON clause. It now asks which customers have matching orders of at least 1000 cents, and the customers table keeps every row. Customer 1’s 800-cent order does not satisfy the match, leaving customer 1 with 1 qualifying order and customers 2 and 3 with 0: [(1, 1), (2, 0), (3, 0)].
Shift o.cents >= 1000 from ON into a WHERE clause, and customers 2 and 3 vanish entirely, shrinking the result to [(1, 1)]. In SQL’s logical evaluation order, FROM and JOIN ... ON run before WHERE. Placing o.cents >= 1000 inside WHERE tests the null-padded rows for customers 2 and 3 where o.cents = NULL; because NULL >= 1000 evaluates to UNKNOWN (which acts as falsy in WHERE), the filter strips them out and turns your LEFT JOIN into an INNER JOIN.
Neither placement is always right, since each one answers a different question. Use ON for a restriction on the optional table when the report must keep the entire left-hand population (all customers, showing how many large orders each placed). Use WHERE when you truly want to narrow the final rows (only customers who placed at least one large order), or when you deliberately hunt for unmatched rows with WHERE o.id IS NULL, known as an anti-join.
Check the key relationship
The relationship is one-to-many: customers.id identifies exactly one customer (1 row per customer), while orders.customer_id may repeat across many orders. Joining customers with orders therefore changes the row grain: each matched order gets its own row, and each customer without a match still contributes one row. Join a second one-to-many child table in the same query, such as support_tickets with three tickets for customer 1, and customer 1’s two orders cross-multiply with those three tickets into 2 × 3 = 6 rows! Summing o.cents over those six rows would triple customer 1’s revenue.
For metrics from both child tables (orders and support_tickets), first aggregate each by customer using GROUP BY customer_id in subqueries or common table expressions (WITH ... AS (...)), then join the summaries to customers. SELECT DISTINCT hides duplicate rows, not inflated SUM() or COUNT() totals.
Extend the exercise
Add the rows below to the SQL fixture before the queries run. Update the matching assert expectations as you go: the original assertions cover only the original two orders, so leaving them untouched makes the script halt before it prints the new results.
Insert order (12, 2, 900) giving customer 2 a purchase of 900 cents, and predict both outputs before executing the script: all_orders updates to [(1, 2), (2, 1), (3, 0)], whereas large_orders stays [(1, 1), (2, 0), (3, 0)] since 900 falls under 1000. Although customer 2 now has a recorded order, the ON predicate o.cents >= 1000 filters out that match while keeping customer 2 at a count of 0. Next, insert (13, 2, 1500) and confirm that large_orders updates to [(1, 1), (2, 1), (3, 0)].
After both added orders, assert all_orders == [(1, 2), (2, 2), (3, 0)] and large_orders == [(1, 1), (2, 1), (3, 0)].
Finally, add a fourth customer (4, 'Maple') sharing customer 1’s display name, and append (4, 0) to both expected result lists. Because ON o.customer_id = c.id and GROUP BY c.id use the primary key c.id, not c.name, the two 'Maple' customers stay separate. To show names too, write SELECT c.id, c.name, COUNT(o.id) ... GROUP BY c.id, c.name and put the name in each expected tuple. Names make poor join or grouping keys: they collide and they change.
Next, use GROUP BY and HAVING to filter aggregates or learn why window functions preserve detail rows.
Source: SQLite SELECT documentation describes join processing, ON versus WHERE evaluation order, and grouping.
Download the complete example. Save the file before running it; the guide above names the required runtime.
Updated November 17, 2026: replaced the overview diagram with the fixture’s actual rows, including the NULL-padded rows that show why COUNT(o.id) = 0.
Keep building
- Python SQLite: transactions and parameterized queries
Create a small expense database, insert safely, and prove a failed transaction does not leave partial work.
- SQL GROUP BY: make the unit of analysis explicit
Build a category report with COUNT, SUM, HAVING, and deterministic ordering on a supplied dataset.
- Pandas merge: prevent accidental row multiplication
Join orders to customers with explicit keys, cardinality validation, and a report of unmatched records.