βœ–οΈ CROSS JOIN – Combining Every Row from Both Tables<

(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_idcolor_name
1Red
2Blue

πŸ› οΈ shapes table:

shape_idshape_name
1Circle
2Square

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_nameshape_name
RedCircle
RedSquare
BlueCircle
BlueSquare

πŸ” 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top