Careeroza
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
| FirstName | ProductName |
|---|---|
| Ananya | Espresso Beans 1kg |
| Ananya | Green Tea 100 bags |
| James | Espresso Beans 1kg |
| James | Green 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
| Size | Colour |
|---|---|
| L | Black |
| M | Black |
| S | Black |
| L | White |
| M | White |
| S | White |
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
| FirstName | Month | Sales |
|---|---|---|
| David | 2024-01 | 89.9 |
| David | 2024-02 | 56.25 |
| David | 2024-03 | 27 |
| Rahul | 2024-01 | 0 |
| Rahul | 2024-02 | 0 |
| Rahul | 2024-03 | 0 |
| Sara | 2024-01 | 245.5 |
| Sara | 2024-02 | 412 |
| Sara | 2024-03 | 320.75 |