Skip to main content

SQL Server: Unlocking the Power of Combinations: The CROSS JOIN Magic Unveiled!

In T-SQL (Transact-SQL), a Cross Join or Cartesian Join is used to combine all rows from two or more tables, resulting in a Cartesian product. It means that each row from the first table will be matched with every row from the second table. Please do keep in mind that cross joins can quickly generate large result sets, so they should be used with caution and when necessary.

Sample Data to Demo Cross Join

You can use this DB Fiddle to follow along and practice cross join

Here's an example of a cross join in T-SQL:

Let's say we have two tables: "Product" and "Color" with the following data:

Table: Product

ProductIdProductName
1T-shirt
2Jeans
3Sneakers

Table: Color

ColorIdColorName
101Red
102Blue
103Green

Cross Join to Generate All Possible Product Color Combinations

Now, let's perform a cross join between these two tables:

The CROSS JOIN query returns the Cartesian product of the sets of records from Product and Color tables.
SELECT *
FROM Product
CROSS JOIN Color
ORDER BY ProductId
,ColorId;

Instead of using the explicit CROSS JOIN keyword, you can simply list the tables separated by a comma to achieve the same result.

The alternative way to perform a cross join in T-SQL.
SELECT *
FROM Product
,Color
ORDER BY ProductId
,ColorId;

The result of this cross join will be:

ProductIdProductNameColorIdColorName
1T-shirt101Red
1T-shirt102Blue
1T-shirt103Green
2Jeans101Red
2Jeans102Blue
2Jeans103Green
3Sneakers101Red
3Sneakers102Blue
3Sneakers103Green

As you can see, each row from the "Product" table is combined with every row from the "Color" table, resulting in a total of nine rows (3 x 3) in the output. The ProductId and ProductName are repeated for each color in the result set.

This cross join helps in creating a matrix of all possible combinations of products and colors. Again, keep in mind that cross joins can quickly generate large result sets, so use them judiciously and consider applying filtering or other methods to limit the output as needed.