What is the difference between CROSS JOIN and FULL OUTER JOIN in SQL Server?
Are they the same, or not? Please explain. When would one use either of these?
What is the difference between CROSS JOIN and FULL OUTER JOIN in SQL Server?
Are they the same, or not? Please explain. When would one use either of these?
A cross join produces a cartesian product between the two tables, returning all possible combinations of all rows. It has no
on
clause because you're just joining everything to everything.A
full outer join
is a combination of aleft outer
andright outer
join. It returns all rows in both tables that match the query'swhere
clause, and in cases where theon
condition can't be satisfied for those rows it putsnull
values in for the unpopulated fields.This wikipedia article explains the various types of joins with examples of output given a sample set of tables.
For SQL Server,
CROSS JOIN and FULL OUTER JOIN
are different.CROSS JOIN
is simply Cartesian Product of two tables, irrespective of any filter criteria or any condition.FULL OUTER JOIN
gives unique result set ofLEFT OUTER JOIN and RIGHT OUTER JOIN
of two tables. It also needs ON clause to map two columns of tables.Hi they are the same concepts apart from the NULL value returned.
See below:
Here is an example where both the FULL OUTER JOIN and CROSS JOIN return the same result set without NULL returned. Please note the 1 = 1 in the ON clause for the FULL OUTER JOIN:
Cross join :Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 3 rows and table B has 2 rows, a CROSS JOIN will result in 6 rows. There is no relationship established between the two tables – you literally just produce every possible combination.
Full outer Join : A FULL OUTER JOIN is neither "left" nor "right"— it's both! It includes all the rows from both of the tables or result sets participating in the JOIN. When no matching rows exist for rows on the "left" side of the JOIN, you see Null values from the result set on the "right." Conversely, when no matching rows exist for rows on the "right" side of the JOIN, you see Null values from the result set on the "left."
I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:
If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).
EDIT:
From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.