CodeOath
← All posts
SQL70 min total · 18 parts

SQL Fundamentals: Joins, NULL, Aggregate Functions, and Subqueries

Contents — Part 4 of 18: Cross Joins and the Cartesian Product
Part 4 of 18 · ~1 min

Cross Joins and the Cartesian Product

A CROSS JOIN has no ON condition at all — it pairs every row on the left with every row on the right, producing (rows in A) × (rows in B) output rows:

SELECT e.name, d.dept
FROM Employees e
CROSS JOIN Departments d;
-- 5 employees × 4 departments = 20 rows

Genuine uses are rare but real: generating every combination of two small dimension tables (e.g., every product × every size), or building a calendar of dates. Far more often, a CROSS JOIN shows up by accident — someone lists two tables in FROM separated by a comma and forgets the WHERE clause that was supposed to relate them:

-- Almost certainly a bug: an implicit cross join, not an intentional one
SELECT e.name, d.dept
FROM Employees e, Departments d;
-- silently returns 20 rows instead of the intended per-department match

This is one reason modern style strongly prefers explicit JOIN ... ON syntax over comma-separated FROM lists — a missing join condition is a glaring, obvious bug in the JOIN form, but an easy-to-miss typo in the comma form.