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?
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
One thing that might not always be obvious to some is that a cross join with an empty table (or result set) results in empty table (M x N; hence M x 0 = 0)
A full outer join will always have rows unless both M and N are 0.
They are the same concepts, apart from the NULL value returned.
See below:
declare @table1 table( col1 int, col2 int );
insert into @table1 select 1, 11 union all select 2, 22;
declare @table2 table ( col1 int, col2 int );
insert into @table2 select 10, 101 union all select 2, 202;
select
t1.*,
t2.*
from @table1 t1
full outer join @table2 t2 on t1.col1 = t2.col1
order by t1.col1, t2.col1;
/* full outer join
col1 col2 col1 col2
----------- ----------- ----------- -----------
NULL NULL 10 101
1 11 NULL NULL
2 22 2 202
*/
select
t1.*,
t2.*
from @table1 t1
cross join @table2 t2
order by t1.col1, t2.col1;
/* cross join
col1 col2 col1 col2
----------- ----------- ----------- -----------
1 11 2 202
1 11 10 101
2 22 2 202
2 22 10 101
*/
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 of LEFT OUTER JOIN and RIGHT OUTER JOIN
of two tables. It also needs ON clause to map two columns of tables.
Table 1 contains 10 rows and Table 2 contains 20 rows with 5 rows matching on specific columns.
Then
CROSS JOIN
will return 10*20=200 rows in result set.
FULL OUTER JOIN
will return 25 rows in result set.
FULL OUTER JOIN
(or any other JOIN) always returns result set with less than or equal toCartesian Product number
.Number of rows returned by
FULL OUTER JOIN
equal to (No. of Rows byLEFT OUTER JOIN
) + (No. of Rows byRIGHT OUTER JOIN
) - (No. of Rows byINNER JOIN
).