(because sometimes you want every possible combination of rows)
π§ Quick Syntax
SELECT columns
FROM table1
CROSS JOIN table2;
This tells SQL:
“Give me every possible combination of rows from both tables.”
π Imagine You Have Two Tables:
π§ colors
table:
color_id | color_name |
---|---|
1 | Red |
2 | Blue |
π οΈ shapes
table:
shape_id | shape_name |
---|---|
1 | Circle |
2 | Square |
In this case, we have:
– 2 colors: Red, Blue
– 2 shapes: Circle, Square
π What Does a CROSS JOIN Do?
A CROSS JOIN creates every possible combination of rows between the two tables.
It takes every row from the colors
table and combines it with every row from the shapes
table.
π§ CROSS JOIN Example
Letβs say we want to create a list of all possible combinations of colors and shapes.
SELECT colors.color_name, shapes.shape_name
FROM colors
CROSS JOIN shapes;
What will happen is:
– The first color (Red
) will be combined with both shapes: Circle
and Square
– Then, the second color (Blue
) will be combined with both shapes: Circle
and Square
.
β Result:
color_name | shape_name |
---|---|
Red | Circle |
Red | Square |
Blue | Circle |
Blue | Square |
π Why Use CROSS JOIN?
- When you need to generate combinations of data β like product bundles or testing combinations of options.
- Be cautious: If you have large tables, a CROSS JOIN can quickly multiply the number of rows. For example, 100 rows in one table and 50 rows in another will give you 5,000 rows in your result set.
π§ Recap
CROSS JOIN
gives you every possible combination of rows from both tables.- Itβs perfect for generating combinations, like creating product bundles or testing different combinations of options.
- Be careful with large tables, as it can generate huge result sets.