What does a CROSS JOIN produce, and how do I work out how many rows I will get?
A CROSS JOIN pairs every row of the first table with every row of the second. There is no join condition, so the result is the Cartesian product: rows_left multiplied by rows_right. Three customers and four products give twelve rows, none of them related to each other.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR(120) NOT NULL
);
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name VARCHAR(60) NOT NULL
);
INSERT INTO products (id, name) VALUES
(1, 'Mechanical Keyboard'),
(2, 'USB-C Hub'),
(3, '27-inch Monitor');
INSERT INTO categories (id, name) VALUES
(1, 'peripherals'),
(2, 'displays');
SELECT p.name AS product, c.name AS category
FROM products AS p
CROSS JOIN categories AS c
ORDER BY p.name, c.name;Six rows come back: the Mechanical Keyboard with both categories, the USB-C Hub with both, and the 27-inch Monitor with both. Every product appears once per category, and the combinations are nonsense — a monitor is not a peripheral — which is exactly why an unqualified cross join is nearly always a mistake.
The row count is simply the product of the two input counts, so the danger is exponential: ten tables of ten rows joined without conditions gives ten billion rows, and the query will either run for a very long time or exhaust memory before anyone notices.
How to tell that you have written one by accident. The comma join without a WHERE clause produces the same thing. And a join whose ON clause is always true — ON 1 = 1, or a predicate that does not involve either table — is a cross join in disguise. If a query suddenly returns far more rows than expected, look for a join condition that references the wrong column, because a join key that matches too many values produces the same symptom as a missing condition.