Sunday, August 11, 2019

Difference between left join and right join in SQL Server



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



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...