What is the difference between CROSS JOIN and FULL OUTER JOIN in SQL, and when to use each?
sobes.tech AI
Answer from AI
CROSS JOIN and FULL OUTER JOIN are different types of table joins in SQL with different purposes:
-
CROSS JOIN is the Cartesian product of two tables. Each row from the first table is combined with each row from the second table. It is used when you need to get all possible combinations of rows.
Example:
SELECT * FROM A CROSS JOIN B;If A has 3 rows and B has 2, the result will be 6 rows.
-
FULL OUTER JOIN combines rows from both tables, including all rows even if there are no matches in the other table. Where there is no match, the fields from the other table will be filled with NULL.
Used when you want to get all data from both tables while preserving information about unmatched rows.
Example:
SELECT * FROM A FULL OUTER JOIN B ON A.id = B.id;
When to use:
- CROSS JOIN — for generating all possible pairs, for example, when creating schedules or combinations.
- FULL OUTER JOIN — when you need to combine data from two tables and keep all records, even if there are no matches.
Thus, CROSS JOIN increases the number of rows, while FULL OUTER JOIN combines data while preserving all records.