In SQL, a CROSS JOIN
is a type of join that returns the Cartesian product of two tables. This means that it combines each row from the first table with every row from the second table. The result is a new table where the number of rows is the product of the number of rows in the two tables being joined.
Syntax
Example
Consider two tables:
Table1:
id | name |
---|---|
1 | Alice |
2 | Bob |
Table2:
category | value |
---|---|
A | 10 |
B | 20 |
Performing a CROSS JOIN
on these tables would yield:
Result:
id | name | category | value |
---|---|---|---|
1 | Alice | A | 10 |
1 | Alice | B | 20 |
2 | Bob | A | 10 |
2 | Bob | B | 20 |
Key Points
-
Cartesian Product: The
CROSS JOIN
generates a Cartesian product of the tables involved. If Table1 hasm
rows and Table2 hasn
rows, the result will havem * n
rows. -
No Join Condition: Unlike
INNER JOIN
orLEFT JOIN
, theCROSS JOIN
does not require a condition to match rows from the tables. -
Potential for Large Results: Be cautious when using
CROSS JOIN
with large tables, as it can produce a very large number of rows and potentially impact performance. -
Usage: It's often used for generating combinations of data, such as creating test data or exploring all possible combinations of two sets.
Alternatives
INNER JOIN
: If you need to combine rows based on related columns, useINNER JOIN
with a condition.OUTER JOIN
: For combining rows with specific conditions, including unmatched rows, useLEFT JOIN
,RIGHT JOIN
, orFULL OUTER JOIN
.