T-SQL Tutorial

SQL Server CROSS JOIN


In SQL Server, a CROSS JOIN is a type of join operation that returns the Cartesian product of two tables. A Cartesian product is formed by combining each row of one table with every row of the other table, resulting in a result set that contains all possible combinations of the two tables.


Syntax

The syntax for a CROSS JOIN in SQL Server is as follows:

SELECT *
FROM table1
CROSS JOIN table2;

In this syntax, table1 and table2 are the two tables being joined. The * operator specifies that all columns from both tables should be included in the result set.


Example

Here is an example of a CROSS JOIN in SQL Server:

SELECT *
FROM customers
CROSS JOIN orders
ORDER BY customer_id;

In this example, the customers table has the following data:

customer_idcustomer_name
1John
2Michael
3Brad

And the orders table has the following data:

order_idorder_date
10001-01-2021
10101-02-2021
10201-03-2021

The result of the query will be a new table with all possible combinations of the rows from the customers table and the orders table, resulting in 9 rows, (3*3).

customer_idcustomer_nameorder_idorder_date
1John10001-01-2021
1John10101-02-2021
1John10201-03-2021
2Michael10001-01-2021
2Michael10101-02-2021
2Michael10201-03-2021
3Brad10001-01-2021
3Brad10101-02-2021
3Brad10201-03-2021

It is important to note that in this example, we are using the wildcard (*) in the SELECT statement to return all columns from both the customers and orders table. In practice, you would usually specify the columns you want to return in the SELECT statement, rather than using the wildcard.


Conclusion

It is important to note that a cross join can result in a very large number of rows, and should be used with caution, especially when working with large tables. It can be useful for some types of reporting or data analysis, but in most cases a more specific join, such as an inner join or left join, is more appropriate.

CROSS JOINs can be useful in a variety of scenarios, such as generating test data, creating pivot tables, or performing complex calculations. They can also be used to combine data from unrelated tables, although this should be done with caution as it can lead to confusing or misleading results.

Overall, the CROSS JOIN is a powerful tool for SQL Server developers and DBAs, but it should be used carefully and only in situations where it makes sense to do so.