CROSS JOIN: Concept
Module: Joins & Relationships
CROSS JOIN returns the cartesian product of two tables - every possible combination of rows. Unlike other joins, CROSS JOIN has no ON clause because it doesn't match rows based on conditions. It simply pairs every row from the left table with every row from the right table. Think of it as a multiplication table: 3 colors × 4 sizes = 12 combinations.
**What is CROSS JOIN?**
CROSS JOIN combines every row from left table with every row from right table, creating all possible combinations.
No matching logic. No ON clause. Just pure multiplication.
**How It Works:**
1. Take first row from left table
2. Pair it with EVERY row from right table
3. Take second row from left table
4. Pair it with EVERY row from right table
5. Repeat for all left table rows
Result: N × M rows (N = left rows, M = right rows)
**Simple Example:**
colors table: Red, Blue (2 rows)
sizes table: Small, Medium, Large (3 rows)
SELECT * FROM colors CROSS JOIN sizes;
Result: 2 × 3 = 6 rows
- Red + Small
- Red + Medium
- Red + Large
- Blue + Small
- Blue + Medium
- Blue + Large
Every color paired with every size.
**No ON Clause:**
CROSS JOIN syntax:
SELECT * FROM table1 CROSS JOIN table2;
No ON clause needed (or allowed). The join is unconditional.
Compare to INNER JOIN:
SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.foreign_key;
INNER JOIN needs ON clause to specify matching condition.
**Calculating Result Size:**
Critical skill: predict result size before running query.
Formula: Left rows × Right rows = Result rows
Examples:
- 10 products × 3 sizes = 30 rows
- 100 customers × 12 months = 1,200 rows
- 1,000 employees × 365 days = 365,000 rows
- 10,000 users × 10,000 products = 100,000,000 rows (100 million!)
Last example shows danger: CROSS JOIN can explode result size.
**When to Use CROSS JOIN:**