Skip to main content

CROSS JOIN

Learning Focus

Use this lesson to understand CROSS JOIN — generating the Cartesian product of two tables.

Concept Overview

A CROSS JOIN returns every possible combination of rows from two tables. If table A has 3 rows and table B has 4 rows, the result has 12 rows.

Table A: [r1, r2, r3]   ×   Table B: [c1, c2, c3, c4]
= 12 combinations

Examples

Example 1: Generate All Size-Color Combinations

CREATE TABLE sizes  (size  VARCHAR);
CREATE TABLE colors (color VARCHAR);

INSERT INTO sizes VALUES ('S'), ('M'), ('L'), ('XL');
INSERT INTO colors VALUES ('Red'), ('Blue'), ('Green');

-- All 12 combinations
SELECT size, color FROM sizes CROSS JOIN colors ORDER BY size, color;

Example 2: Date x Category Matrix

-- Generate a report scaffold for every month x department
SELECT d.month_label, dept.department
FROM (SELECT '2024-01' AS month_label UNION ALL SELECT '2024-02' UNION ALL SELECT '2024-03') d
CROSS JOIN (SELECT DISTINCT department FROM employees) dept
ORDER BY month_label, department;

Example 3: CROSS JOIN with range() (DuckDB-specific)

-- Generate combinations using range()
SELECT a.n AS n1, b.n AS n2
FROM (SELECT unnest(range(1,4)) AS n) a
CROSS JOIN (SELECT unnest(range(1,4)) AS n) b
ORDER BY n1, n2;

When to Use CROSS JOIN

Use CaseExample
Combinatorial gridsSize × Color product variants
Report scaffoldingAll months × all categories
Test data generationRandom pairings
Distance matricesEvery city to every city

Common Pitfalls

PitfallConsequencePrevention
Accidental CROSS JOINRow explosion — billions of rowsAlways verify join type; use EXPLAIN
No WHERE to filter the productUnusably large resultAdd filtering conditions after cross join
Confusing CROSS JOIN with INNER JOINWrong business logicCROSS JOIN = no join condition by design

Quick Reference

SELECT a.col, b.col FROM a CROSS JOIN b;
SELECT * FROM t1, t2; -- implicit CROSS JOIN (avoid this style)

What's Next