Difference between left join and right join in SQL Server

Pankaj Agarwal picture Pankaj Agarwal · Jan 17, 2011 · Viewed 299.8k times · Source

I know about joins in SQL Server.

For example. There are two tables Table1, Table2.

Their table structures are the 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 the above SQL statements.

Answer

Péter Török picture Péter Török · Jan 17, 2011
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.