sq12

This page covers both the left outer join, the right outer join, and the full outer join, and explains the differences between them.
There are some occasions where you would need to use a left outer join or a right outer join, and others where you would need a full outer join. The join type you use will depend on the situation and what data you need to return.

Left Outer Join

Use this when you only want to return rows that have matching data in the left table, even if there's no matching rows in the right table.

Example SQL statement

SELECT * FROM Individual AS Ind
LEFT JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId;

Source Tables

Left Table
IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike
Right Table
IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor
10Administrator

Result

IndividualIdFirstNameLastNameUserNameIndividualIdAccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL

Right Outer Join

Use this when you only want to return rows that have matching data in the right table, even if there's no matching rows in the left table.

Example SQL statement

SELECT * FROM Individual AS Ind
RIGHT JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId;

Source Tables

Left Table
IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike
Right Table
IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor
10Administrator

Result

IndividualIdFirstNameLastNameUserNameIndividualIdAccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
NULLNULLNULLNULL10Administrator

Full Outer Join

Use this when you want to all rows, even if there's no matching rows in the right table.

Example SQL statement

SELECT * FROM Individual AS Ind
FULL JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId;

Source Tables

Left Table
IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike
Right Table
IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor
10Administrator

Result

IndividualIdFirstNameLastNameUserNameIndividualIdAccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL
NULLNULLNULLNULL10Administrator

No comments: