SQL Practice Logo

SQLPractice Online

CROSS JOIN: Performance

Module: Joins & Relationships

**Critical Performance Warnings:**

1. **Result Size Explosion:**

CROSS JOIN can create massive result sets:

Small tables (safe):

10 rows × 10 rows = 100 rows

Medium tables (caution):

1,000 rows × 1,000 rows = 1,000,000 rows

Large tables (danger!):

10,000 rows × 10,000 rows = 100,000,000 rows

Always calculate: N × M before running query.

2. **Memory and Network Impact:**

Large cartesian products:

• Consume massive memory

• Slow network transfer

• Can crash applications

• May timeout

Example: 1M rows result = 100+ MB data transfer

3. **Use WHERE to Limit Results:**

Bad (huge result):

SELECT * FROM products CROSS JOIN sizes;

-- 10,000 products × 10 sizes = 100,000 rows

Good (filtered):

SELECT * FROM products CROSS JOIN sizes

WHERE products.category = 'Clothing';

-- 500 clothing products × 10 sizes = 5,000 rows

4. **Avoid CROSS JOIN on Large Tables:**

Never do this:

SELECT * FROM large_table1 CROSS JOIN large_table2;

If you must, filter aggressively:

SELECT * FROM large_table1 CROSS JOIN large_table2

WHERE large_table1.id < 100 -- Limit to 100 rows

AND large_table2.active = true;

5. **Consider Alternatives:**

Instead of CROSS JOIN, consider:

• Generate combinations in application code

• Use recursive CTEs for sequences

• Pre-compute combinations in a table

• Use window functions for some scenarios

6. **When CROSS JOIN is Appropriate:**

Safe scenarios: