CROSS JOIN

The SQL CROSS JOIN

CROSS JOIN returns every combination of rows from both tables. If table1 has m rows and table2 has n rows, the result has m × n rows. There is no ON clause.

SELECT column_name(s)
FROM table1
CROSS JOIN table2;

Example

Example

Every employee in Support paired with every Beverages product (2 × 2 = 4 rows):

SELECT e.FirstName, p.ProductName
FROM Employees e
CROSS JOIN Products p
WHERE e.Department = 'Support' AND p.Category = 'Beverages';

Result: 4 rows

FirstNameProductName
AnanyaEspresso Beans 1kg
AnanyaGreen Tea 100 bags
JamesEspresso Beans 1kg
JamesGreen Tea 100 bags

Accidental Cross Joins

A comma join without a WHERE condition is a cross join. On two tables of 100,000 rows each, it produces 10 billion rows and can bring a server down.

-- missing join condition: 8 customers x 8 orders = 64 rows!
SELECT * FROM Customers, Orders;

Generating Combinations

Example

Build a size × colour list for a T-shirt catalogue:

WITH Sizes(Size) AS (VALUES ('S'), ('M'), ('L')),
     Colours(Colour) AS (VALUES ('Black'), ('White'))
SELECT Size, Colour
FROM Sizes
CROSS JOIN Colours
ORDER BY Colour, Size;

Result: 6 rows

SizeColour
LBlack
MBlack
SBlack
LWhite
MWhite
SWhite

Filling Gaps in Reports

Example

Every employee × every month, so months with no sales still show 0:

WITH Months(m) AS (VALUES ('2024-01'), ('2024-02'), ('2024-03'))
SELECT e.FirstName, Months.m AS Month,
       COALESCE(SUM(o.Amount), 0) AS Sales
FROM Employees e
CROSS JOIN Months
LEFT JOIN Orders o
  ON o.EmployeeID = e.EmployeeID AND strftime('%Y-%m', o.OrderDate) = Months.m
WHERE e.Department = 'Sales'
GROUP BY e.FirstName, Months.m
ORDER BY e.FirstName, Months.m;

Result: 9 rows

FirstNameMonthSales
David2024-0189.9
David2024-0256.25
David2024-0327
Rahul2024-010
Rahul2024-020
Rahul2024-030
Sara2024-01245.5
Sara2024-02412
Sara2024-03320.75