🔀 SQL CROSS JOIN – Cartesian Product Explained with Examples

A CROSS JOIN in SQL returns the Cartesian product of two tables. That means it matches every row from the first table with every row from the second table.

This is useful for generating combinations, testing scenarios, or pairing each item in one list with every item in another.


📘 What is SQL CROSS JOIN?

A CROSS JOIN creates all possible combinations of rows between two tables.
If table A has m rows and table B has n rows, the result will have m × n rows.

📌 No ON condition is needed.


🧾 Syntax of SQL CROSS JOIN

SELECT *
FROM table1
CROSS JOIN table2;

🔁 Every row in table1 is combined with every row in table2.


✅ Real-World Example: Colors & Sizes

Suppose you have two tables:

colors

color
Red
Blue

sizes

size
Small
Medium
Large

Now run this:

SELECT 
  c.color,
  s.size
FROM colors c
CROSS JOIN sizes s;

🧾 Result:

colorsize
RedSmall
RedMedium
RedLarge
BlueSmall
BlueMedium
BlueLarge

🎯 This is ideal for generating a product variant matrix.


🎯 Use Cases for SQL CROSS JOIN

  • 📦 Generating product combinations (e.g., color × size)
  • 📅 Creating calendar templates (dates × employees)
  • 🎲 Simulating all test scenarios (e.g., browser × device)
  • 📊 Preparing reporting grids (e.g., region × category)

🔄 CROSS JOIN vs INNER JOIN

FeatureINNER JOINCROSS JOIN
Requires join conditionON clause needed❌ No join condition
Output sizeMatches onlyAll combinations (m × n)
Use caseMatch related dataCombine all possibilities

⚠️ Performance Note

CROSS JOINs can produce a very large result set, especially if both tables have many rows.
Always use them with purpose and care.


🧠 Filter After CROSS JOIN

You can use WHERE after a CROSS JOIN to limit results:

SELECT *
FROM products
CROSS JOIN regions
WHERE region = 'North America';

This narrows down the combinations after they are created.


📝 Summary

  • SQL CROSS JOIN returns a Cartesian product – every combination of rows
  • Use it to generate all possible pairings between two datasets
  • Be cautious – output size grows quickly with larger tables