I've never used right join
before and never thought I could actually need it, and it seems a bit unnatural. But after I thought about it, it could be really useful in the situation, when you need to outer join one table with intersection of many tables, so you have tables like this:
And want to get result like this:
Or, in SQL (MS SQL Server):
declare @temp_a table (id int)
declare @temp_b table (id int)
declare @temp_c table (id int)
declare @temp_d table (id int)
insert into @temp_a
select 1 union all
select 2 union all
select 3 union all
select 4
insert into @temp_b
select 2 union all
select 3 union all
select 5
insert into @temp_c
select 1 union all
select 2 union all
select 4
insert into @temp_d
select id from @temp_a
union
select id from @temp_b
union
select id from @temp_c
select *
from @temp_a as a
inner join @temp_b as b on b.id = a.id
inner join @temp_c as c on c.id = a.id
right outer join @temp_d as d on d.id = a.id
id id id id
----------- ----------- ----------- -----------
NULL NULL NULL 1
2 2 2 2
NULL NULL NULL 3
NULL NULL NULL 4
NULL NULL NULL 5
So if you switch to the left join
, results will not be the same.
select *
from @temp_d as d
left outer join @temp_a as a on a.id = d.id
left outer join @temp_b as b on b.id = d.id
left outer join @temp_c as c on c.id = d.id
id id id id
----------- ----------- ----------- -----------
1 1 NULL 1
2 2 2 2
3 3 3 NULL
4 4 NULL 4
5 NULL 5 NULL
The only way to do this without the right join is to use common table expression or subquery
select *
from @temp_d as d
left outer join (
select *
from @temp_a as a
inner join @temp_b as b on b.id = a.id
inner join @temp_c as c on c.id = a.id
) as q on ...