Sub topic 7
Cross joins and the Cartesian product
This chapter assumes you can write SELECT, WHERE, and ORDER BY, and that you can use INNER JOIN and LEFT JOIN with an ON condition. It also assumes you know what primary and foreign keys are. The earlier chapters in this tutorial covered self joins. Here you meet a different kind of join, one that has no matching condition at all.
How a normal join differs
An INNER JOIN takes a row from the left table and looks for right-table rows that satisfy the ON condition. Rows that fail the condition are dropped. The ON clause acts as a filter on the pairs the database could form.
A cross join skips the filter. It forms every possible pair of one left row and one right row and returns all of them. The result is called the Cartesian product of the two tables, named after the mathematical operation of the same name.
The Cartesian product by example
Create two small tables, one for sizes and one for colors.
CREATE TABLE sizes (size VARCHAR(2));
CREATE TABLE colors (color VARCHAR(10));
INSERT INTO sizes (size) VALUES ('S'), ('M'), ('L');
INSERT INTO colors (color) VALUES ('red'), ('blue');
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c;The query has no ON clause. Every size appears with every color, so the result has 6 rows:
| size | color |
|---|---|
| S | red |
| S | blue |
| M | red |
| M | blue |
| L | red |
| L | blue |
The row order is not guaranteed unless you add ORDER BY. Your database may return the same six rows in a different sequence.
Predicting the row count
The size of a cross join follows one rule:
result rows = rows in the left input × rows in the right input
With 3 sizes and 2 colors you get 6 rows. You can check this without printing the rows.
SELECT COUNT(*) AS pair_count
FROM sizes s
CROSS JOIN colors c;This returns 6. The rule extends to more tables. Cross joining a third table with 4 rows gives 3 × 2 × 4 = 24 rows. Each extra table multiplies the count again, which is why a cross join of several moderately sized tables grows fast.
| Left rows | Right rows | Result rows |
|---|---|---|
| 3 | 2 | 6 |
| 10 | 10 | 100 |
| 1,000 | 1,000 | 1,000,000 |
| 100,000 | 100,000 | 10,000,000,000 |
The last row shows why you should predict the count before you run a cross join on real tables.
Things that follow from the rule
The multiplication rule explains several behaviors that surprise people.
An empty input gives an empty result
If either table has zero rows, the product is zero rows, because anything times 0 is 0.
CREATE TABLE materials (material VARCHAR(10));
SELECT s.size, m.material
FROM sizes s
CROSS JOIN materials m;The materials table has no rows, so this query returns no rows at all. This matters in reports. If a lookup table is accidentally empty, a cross join silently removes every row from the result. It does not raise an error.
Duplicates multiply
A cross join does not remove duplicates. If sizes contained 'M' twice, each 'M' would pair with each color. You would get 4 × 2 = 8 rows, and M, red and M, blue would each appear twice. Use SELECT DISTINCT or fix the source data if you want unique combinations.
NULL values are just values here
A cross join never compares columns, so NULL behaves like any other value. A row containing NULL is paired with every row from the other table. The usual trouble with NULL = NULL evaluating to unknown does not arise, because no equality test runs.
Column order and naming
The result contains all columns of the left table followed by all columns of the right table. If both tables have a column with the same name, qualify each one with its alias, as in s.size and c.color. Without qualification the database reports an ambiguous column error.
A cross join with a filter is an inner join
The Cartesian product is the starting point for every other join. Conceptually, an inner join builds all pairs, then keeps those that satisfy ON. Using the employees table from the earlier chapters, you can see this directly.
SELECT e.name AS employee, m.name AS manager
FROM employees e
CROSS JOIN employees m
WHERE e.manager_id = m.id;The cross join produces 4 × 4 = 16 pairs. The WHERE condition keeps only the 3 pairs where the manager id matches, which is the same result as the inner self join. Ava has no manager, so she does not appear.
Database optimizers know this equivalence. They do not build all 16 pairs and then filter. They treat the query as an inner join and use indexes where they can. For clarity, write INNER JOIN ... ON when you mean a matching join, and reserve CROSS JOIN for cases where you really want every pair.
Reading the result as a grid
Another way to picture the cross join is a grid. List the left rows down the side and the right rows across the top. Each cell is one result row. A 3 by 2 grid has 6 cells.
| Row | red | blue |
|---|---|---|
| S | S, red | S, blue |
| M | M, red | M, blue |
| L | L, red | L, blue |
When you add a WHERE or ON condition, you are choosing which cells to keep. An INNER JOIN keeps the cells that satisfy the condition. A LEFT JOIN keeps those cells and also guarantees at least one cell for every left row. A cross join keeps all cells.
When a cross join is the right tool
A cross join is correct when you want every combination, with no relationship between the two inputs. Typical uses include:
- Generating a product catalog of every size and color pair.
- Building a calendar of every date and store before joining real data to it.
- Pairing each row with a single-row table of settings or totals. A one-row table multiplies the row count by 1, so nothing grows.
- Producing test data.
Later chapters in this tutorial cover generating combinations and reporting zeros in more detail. For now, remember the shape of the result: it is always the full grid.
Common errors
Check these in order when a result looks too large:
- Compare the result count with the product of the input counts. If it equals the product exactly, no condition is filtering anything.
- Confirm every joined table is linked to at least one other table by a condition.
- Run
SELECT COUNT(*)on each input table to see their sizes.
Some databases refuse a join with no ON condition. MySQL accepts INNER JOIN without ON and treats it as a cross join. PostgreSQL and SQL Server require ON for INNER JOIN, but reject nothing when you write CROSS JOIN explicitly. Writing CROSS JOIN makes your intent visible to the next reader.
Exercise
A table products has 40 rows and a table regions has 5 rows. How many rows does SELECT * FROM products CROSS JOIN regions return? What happens if regions is empty?
Show answer
It returns 40 × 5 = 200 rows. If regions is empty, the result has 0 rows, because 40 × 0 = 0. No error is raised.
Exercise
The employees table has 4 rows. You run SELECT e.name, m.name FROM employees e CROSS JOIN employees m WHERE e.manager_id = m.id. How many rows does the cross join produce before the filter, and how many rows come back after it? Why is Ava missing?
Show answer
The cross join produces 4 × 4 = 16 pairs. The filter keeps 3 rows: Ben with Ava, Chen with Ava, and Dana with Ben. Ava is missing because her manager_id is NULL, and NULL = m.id is never true, so no pair containing her as the employee passes the filter.
Exercise
You have sizes with the three rows S, M, L, plus a second M row added by mistake. You cross join it with colors (red, blue). How many rows come back, and how would you get only the 6 distinct combinations?
Show answer
It returns 4 × 2 = 8 rows, with M, red and M, blue each appearing twice. Use SELECT DISTINCT s.size, c.color FROM sizes s CROSS JOIN colors c to return the 6 distinct combinations, or remove the duplicate row from sizes.