A CROSS JOIN in MySQL produces the Cartesian product of two tables, meaning every row in the first table is paired with every row in the second table. This type of join does not require a specific condition to join the tables. It results in a combination of all rows from both tables, which can result in a large dataset if the tables have many rows.
Syntax
SELECT column_list
FROM table1
CROSS JOIN table2;
Or equivalently:
SELECT column_list
FROM table1, table2;
Use Case
CROSS JOIN is typically used when you need all possible combinations of rows from two tables. This can be useful for generating test data, pairing combinations, or scenarios where every combination is meaningful (e.g., generating schedules, permutations, etc.).
Example: Using the Northwind Database
Let’s consider two tables from the Northwind database:
- Categories table: CategoryID CategoryName 1 Beverages 2 Condiments 3 Confections
- Suppliers table: SupplierID SupplierName 101 Exotic Liquids 102 New Orleans Cajun 103 Grandma’s Kitchen
Query: CROSS JOIN Example
SELECT Categories.CategoryName, Suppliers.SupplierName
FROM Categories
CROSS JOIN Suppliers;
Result:
The query generates all possible combinations of rows from the Categories
and Suppliers
tables.
CategoryName | SupplierName |
---|---|
Beverages | Exotic Liquids |
Beverages | New Orleans Cajun |
Beverages | Grandma’s Kitchen |
Condiments | Exotic Liquids |
Condiments | New Orleans Cajun |
Condiments | Grandma’s Kitchen |
Confections | Exotic Liquids |
Confections | New Orleans Cajun |
Confections | Grandma’s Kitchen |
Key Points
- Cartesian Product: The number of rows in the result is the product of the rows in both tables. For example, if
Categories
has 3 rows andSuppliers
has 3 rows, the result will have 3×3=93 \times 3 = 9 rows. - Performance Impact: Be cautious with large tables, as the Cartesian product can grow exponentially and impact performance.
- Practical Use: Often,
CROSS JOIN
is combined with filtering criteria using aWHERE
clause to reduce the result set.
Adding a Filter
To filter the results, you can add a WHERE
clause:
Query with Filter
SELECT Categories.CategoryName, Suppliers.SupplierName
FROM Categories
CROSS JOIN Suppliers
WHERE Categories.CategoryName = 'Beverages';
Result:
CategoryName | SupplierName |
---|---|
Beverages | Exotic Liquids |
Beverages | New Orleans Cajun |
Beverages | Grandma’s Kitchen |
Difference from Other Joins
- Unlike
INNER JOIN
,LEFT JOIN
, orRIGHT JOIN
, theCROSS JOIN
does not require a matching condition between the two tables. - The result contains all combinations, regardless of any logical relationship between the tables.
Conclusion
While CROSS JOIN
can generate useful combinations, it should be used carefully with large datasets to avoid performance issues.