RSS Feed

SQL Outer Join

Outer joins

Outer joins can be a left, a right, or full outer join.

Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

LEFT JOIN or LEFT OUTER JOIN

The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. [Source]

SQL LEFT JOIN Example

The "Consumers" table:

P_IdLastName FirstNameAddress City
1KumarRamDelhi AAA
2Singh LaxmanChandigarh AAA
3SharmaSameerAmbalaBBB

The "Orders" table:

O_IdOrderNoP_Id
1778953
2446783
3224561
4245621
53476415

Now we want to list all the Consumers and their orders - if any, from the tables above.

We use the following SELECT statement:

SELECT Consumers.LastName, Consumers.FirstName, Orders.OrderNo
FROM Consumers
LEFT JOIN Orders
ON Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName

The result-set will look like this:

LastName FirstNameOrderNo
KumarRam22456
KumarRam24562
SharmaSameer77895
SharmaSameer44678
SinghLaxman

The LEFT JOIN keyword returns all the rows from the left table (Consumers), even if there are no matches in the right table (Orders).

RIGHT JOIN or RIGHT OUTER JOIN

A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

FULL JOIN or FULL OUTER JOIN

A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Why to use outer joins

Use left or right outer joins when you require a complete list of data that is
stored in one of the joined tables in addition to the information that matches the join condition.

When to use outer joins

Use an outer join when you want to find unmatched rows. (because either you want to find missing values from one of the tables, like in this case, or you may want to include all values from your tables even if they are missing values in the other table).