Pankaj Agarwal Pankaj Agarwal - 5 months ago 57
SQL Question

Difference between left join and right join in SQL Server

I know about joins in SQL Server.

For example. there is two tables Table1, Table2.

There table structure are following.

create table Table1 (id int, Name varchar (10))

create table Table2 (id int, Name varchar (10))


Table1 Data as follows:

Id Name
-------------
1 A
2 B


Table2 Data as follows:

Id Name
-------------
1 A
2 B
3 C


If I execute both below mentioned SQL statements, both outputs will be the same

select *
from Table1
left join Table2 on Table1.id = Table2.id

select *
from Table2
right join Table1 on Table1.id = Table2.id


Please explain the difference between left and right join in above sql statements.

Answer
Select * from Table1 left join Table2 ...

and

Select * from Table2 right join Table1 ...

are indeed completely interchangeable. Try however Table2 left join Table1 (or its identical pair, Table1 right join Table2) to see a difference. This query should give you more rows, since Table2 contains a row with an id which is not present in Table1.