THIS IS NOT DUPLICATE QUESTION. I AM NOT ASKING THE DIFFERENCE BETWEEN A LEFT AND RIGHT JOIN. I AM ASKING WHAT CONSTITUTES A "LEFT" TABLE VERSUS A "RIGHT" TABLE
I understand how to write left and outer joins. I am only looking to verify if my understanding of how to determine what constitutes the "left" and "right" table is correct.
The following is a typical definition of a LEFT/RIGHT OUTER JOIN
A LEFT OUTER JOIN contains all records of the "left" table even if it has no matches in the "right" table specified in the join. A RIGHT OUTER JOIN contains all records in the "right" table even if it has no matches in the "left" table.
What I find lacking from this and all definitions I have read is how do you determine which is the left and right table.
The following code creates 2 table variables and populates it with sample data:
DECLARE @widget TABLE
(
WidgetId int,
ColorId int
)
DECLARE @color TABLE
(
ColorId int,
ColorName varchar(15)
)
INSERT INTO @widget
SELECT 1,1
UNION
SELECT 2,NULL
UNION
SELECT 1,2
INSERT INTO @color
SELECT 1,'Red'
UNION
SELECT 2, 'Blue'
Suppose one wants to write a query that returns all widgets. If the widget has a color then that should be included in the query results. The following 2 queries achieve this:
SELECT w.*,c.ColorName FROM @widget w LEFT OUTER JOIN @color c ON w.ColorId = c.ColorId
SELECT w.*,c.ColorName FROM @color c RIGHT OUTER JOIN @widget w ON w.ColorId = c.ColorId
Please verify if the following statement is correct:
For a Left Outer Join
To determine which is the left and right table, write the query on one line with no line breaks.
Looking at the following portion of the Left Outer Join. Because @widget is to the left of the Join statement that makes it the "Left" table. Likewise, @color is the "Right" table.
@widget w LEFT OUTER JOIN @color
For a Right Outer Join
To determine which is the left and right table, write the query on one line with no line breaks.
Looking at the following portion of the Right Outer Join. Because @widget is to the right of the Join statement that makes it the "Right" table. Likewise, @color is the "Left" table.
@color w RIGHT OUTER JOIN @widget