Please refer the below script
declare @table1 table
(
col1 int
)
declare @table2 table
(
col2 int
)
insert into @table1 values(1)
insert into @table1 values(2)
insert into @table1 values(3)
insert into @table1 values(5)
insert into @table1 values(7)
insert into @table2 values(1)
insert into @table2 values(3)
insert into @table2 values(3)
insert into @table2 values(6)
insert into @table2 values(4)
insert into @table2 values(7)
Case 1:
select * from @table1 a left outer join @table2 b on a.col1=b.col2
order by col1
Result 1:
col1 col2
----------- -----------
| 1 | 1 |
| 2 | NULL |
| 3 | 3 |
| 3 | 3 |
| 5 | NULL |
| 7 | 7 |
---------------------------
Case 2:
select * from @table1 a right outer join @table2 b on a.col1=b.col2
order by col2
Result 2:
col1 col2
----------- -----------
| 1 | 1 |
| 3 | 3 |
| 3 | 3 |
| NULL | 4 |
| NULL | 6 |
| 7 | 7 |
---------------------------
Actual Case:
select * from @table1 a full outer join @table2 b on a.col1=b.col2
Actual Result:
col1 col2
----------- -----------
| 1 | 1 |
| 2 | NULL |
| 3 | 3 |
| 3 | 3 |
| 5 | NULL |
| 7 | 7 |
| NULL | 6 |
| NULL | 4 |
---------------------------
Expected Result:
col1 col2
----------- -----------
| 1 | 1 |
| 2 | NULL |
| 3 | 3 |
| 3 | 3 |
| NULL | 4 |
| 5 | NULL |
| NULL | 6 |
| 7 | 7 |
---------------------------
I tried union all with left and right join query but it doubles the result set. Is there a way that I can get this expected output.
Thanks,
Esen.
You can use
to get your desired order. Without an
ORDER BYno ordering is guaranteed.