SQL Tutorial
In SQL, a CROSS JOIN
is used to combine all rows from two or more tables, without a condition to match them. This kind of join returns what's known as the Cartesian Product of the tables involved. If the first table has 'n' rows and the second table has 'm' rows, the result of the CROSS JOIN
will contain n*m
rows.
The syntax for CROSS JOIN
is:
SELECT column_name(s) FROM table1 CROSS JOIN table2;
Example:
Let's consider two tables, Colors
and Sizes
:
Table Colors
:
ID | Color ----------- 1 | Red 2 | Blue 3 | Green
Table Sizes
:
ID | Size ---------- 1 | Small 2 | Medium 3 | Large
If you want to generate all possible combinations of colors and sizes, you can use a CROSS JOIN
:
SELECT Colors.Color, Sizes.Size FROM Colors CROSS JOIN Sizes;
The result would be:
Color | Size ------------- Red | Small Red | Medium Red | Large Blue | Small Blue | Medium Blue | Large Green | Small Green | Medium Green | Large
Note: The CROSS JOIN
keyword in some databases can be omitted and replaced with a comma separating the two tables as follows:
SELECT Colors.Color, Sizes.Size FROM Colors, Sizes;
This will give the same result as the previous CROSS JOIN
example. However, using explicit join syntax (like CROSS JOIN
) is generally recommended for clarity.
Cartesian Product with SQL CROSS JOIN:
SELECT * FROM Table1 CROSS JOIN Table2;
Joining Tables using CROSS JOIN:
SELECT Employees.EmployeeID, Departments.DepartmentName FROM Employees CROSS JOIN Departments;
CROSS JOIN vs INNER JOIN in SQL:
SELECT Employees.EmployeeID, Departments.DepartmentName FROM Employees INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
Using WHERE Clause with CROSS JOIN:
SELECT Employees.EmployeeID, Departments.DepartmentName FROM Employees CROSS JOIN Departments WHERE Employees.Salary > 50000;
Multiple Tables CROSS JOIN in SQL:
SELECT A.Col1, B.Col2, C.Col3 FROM TableA A CROSS JOIN TableB B CROSS JOIN TableC C;
Avoiding Pitfalls with CROSS JOIN:
-- Apply WHERE conditions to limit the result set SELECT * FROM Table1 CROSS JOIN Table2 WHERE Table1.Column1 = 'Value';
SQL CROSS JOIN Examples:
Code Example 1:
SELECT Customers.CustomerID, Products.ProductName FROM Customers CROSS JOIN Products;
Code Example 2:
SELECT A.Col1, B.Col2 FROM TableA A CROSS JOIN TableB B;