Sub topic 2
From every combination to matching rows
An inner join is a cartesian product that has been filtered. This chapter builds that model step by step, so the join syntax in the next chapter reads as a shorthand for something you already understand.
This chapter assumes you can write basic SELECT, FROM, WHERE and ORDER BY queries. It also assumes you know what primary keys and foreign keys are. If you want to run the examples, create the sample tables from the earlier chapter: customers (Ada, Ben, Chloe) and orders (101 to 104).
The cartesian product
Listing two tables in a query without relating them pairs every row of the first table with every row of the second. The result is called the cartesian product. The standard SQL way to ask for it explicitly is CROSS JOIN.
SELECT
c.name,
o.id AS order_id,
o.customer_id,
CASE WHEN o.customer_id = c.id THEN 'yes' ELSE 'no' END AS is_match
FROM customers AS c
CROSS JOIN orders AS o
ORDER BY c.id, o.id;The customers table has 3 rows and orders has 4, so the result has 3 × 4 = 12 rows:
| name | order_id | customer_id | is_match |
|---|---|---|---|
| Ada | 101 | 1 | yes |
| Ada | 102 | 1 | yes |
| Ada | 103 | 2 | no |
| Ada | 104 | NULL | no |
| Ben | 101 | 1 | no |
| Ben | 102 | 1 | no |
| Ben | 103 | 2 | yes |
| Ben | 104 | NULL | no |
| Chloe | 101 | 1 | no |
| Chloe | 102 | 1 | no |
| Chloe | 103 | 2 | no |
| Chloe | 104 | NULL | no |
Most of these pairs are meaningless. Ada paired with order 103 is just two rows that happen to sit next to each other. Only three pairs reflect a real relationship, the ones where the order's customer_id equals the customer's id.
The is_match column is there only to make that visible. A real query does not label the rows. It keeps the matching ones and discards the rest.
How the row count grows
The product always has rows(A) × rows(B) rows. Sizes multiply instead of adding, which is why an accidental cartesian product is dangerous.
| Customers | Orders | Rows in the product |
|---|---|---|
| 3 | 4 | 12 |
| 1,000 | 100,000 | 100,000,000 |
| 50,000 | 2,000,000 | 100,000,000,000 |
Two edge cases follow from the formula:
- If either table is empty, the product is empty, because
0 × n = 0. - If one table has exactly one row, the product has as many rows as the other table, and each row gains the single row's columns.
A third table multiplies again. Crossing customers, orders and a 10-row products table gives 3 × 4 × 10 = 120 rows.
Keeping only the matching pairs
A condition turns the product into something useful. Apply a WHERE filter that compares the foreign key with the key it references:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
CROSS JOIN orders AS o
WHERE o.customer_id = c.id;This returns three rows: Ada with 101, Ada with 102, and Ben with 103. These are exactly the rows marked yes above.
Two things disappear from the output:
- Chloe has no order whose
customer_idis 3, so none of her three pairs passes the filter. - Order 104 has a
NULLcustomer. The comparisonNULL = 1evaluates to unknown, not true, andWHEREkeeps only rows where the condition is true. So order 104 never matches anyone.
The second point is the reason rows with NULL keys vanish from joins. A later chapter covers it in detail. For now, treat "the condition must be true" as the rule for what survives.
The conceptual model
The query above follows three steps in this logical order:
- Form every pairing of rows from the two tables.
- Evaluate the condition on each pair.
- Keep the pairs where the condition is true.
Why the condition matters
The condition is what gives the result its meaning. The database never guesses which columns are related. A foreign key constraint documents the relationship and prevents bad data, but a query still has to say how to pair rows.
Compare two conditions on the same product:
o.customer_id = c.idpairs each order with the customer who placed it. This is the correct condition.o.customer_id <> c.idkeeps the pairs that do not belong together. It is valid SQL and returns 6 rows (9 of the 12 pairs are non-matches, minus the 3 with order 104, whose comparison is unknown), none of which are meaningful.
Also be careful when column types line up by accident. Joining c.id = o.id is legal, because both are integers, but it compares a customer's key with an order's key. It runs without error and returns no rows here. In a database where the id ranges overlap, it would return rows that look plausible and are wrong.
Intentional uses of a cross join
Most queries should not produce a full product, but a few legitimately do. A cross join suits queries that need every combination, such as a size-and-colour grid:
CREATE TABLE sizes (label VARCHAR(10) PRIMARY KEY);
CREATE TABLE colors (label VARCHAR(10) PRIMARY KEY);
INSERT INTO sizes (label) VALUES ('S'), ('M'), ('L');
INSERT INTO colors (label) VALUES ('red'), ('blue');
SELECT s.label AS size, c.label AS color
FROM sizes AS s
CROSS JOIN colors AS c
ORDER BY s.label, c.label;This returns 3 × 2 = 6 rows, one for each variant. Here the multiplication is the goal.
From filtered product to INNER JOIN
Writing CROSS JOIN followed by WHERE works, but it hides the intent. The WHERE clause mixes two jobs: relating the tables and filtering the data. The next chapter introduces INNER JOIN ... ON, which expresses the same operation with the relating condition placed next to the join. For the sample data, these two queries return identical rows:
SELECT c.name, o.id AS order_id
FROM customers AS c
CROSS JOIN orders AS o
WHERE o.customer_id = c.id;
SELECT c.name, o.id AS order_id
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id;Keep the mental picture of the product from this chapter. When a later query returns surprising row counts, you can go back to it and ask which pairs were formed and which condition accepted them.
Exercise
A table students has 40 rows and a table courses has 12 rows. How many rows does SELECT * FROM students CROSS JOIN courses return? If you add WHERE courses.id = students.course_id and every student has a valid course_id, how many rows can you expect, assuming each course id is unique?
Show answer
The cross join returns 40 × 12 = 480 rows. With the condition, each student matches exactly one course, because course ids are unique and every course_id is valid. The result has 40 rows.
Exercise
In the sample data, SELECT * FROM customers CROSS JOIN orders WHERE o.customer_id = c.id is rewritten with the condition o.customer_id IS NULL OR o.customer_id = c.id. Without running it, how many rows does it return, and why?
Show answer
It returns 7 rows. The three real matches still pass (Ada with 101 and 102, Ben with 103). Order 104 has a NULL customer_id, so IS NULL is true for it, and it passes when paired with each of the 3 customers, adding 3 rows. That makes 3 + 3 = 6 rows. Ben's, Ada's and Chloe's pairings with order 104 are those 3, so the total is 6, not 7. The correct answer is 6 rows.