Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some good examples where SQL's OUTER JOIN is used?

I often get asked the questions in an interview that "what is an outer join in SQL"?

While it can be answered, I wonder what might be some classic and good real life examples where a (LEFT) OUTER JOIN is used?

like image 390
nonopolarity Avatar asked Apr 23 '10 12:04

nonopolarity


People also ask

In which cases would you use an outer join in SQL?

We use the SQL OUTER JOIN to match rows between tables. We might want to get match rows along with unmatched rows as well from one or both of the tables.

In which two cases would you use a full outer join?

An full outer join is a method of combining tables so that the result includes unmatched rows of both tables. If you are joining two tables and want the result set to include unmatched rows from both tables, use a FULL OUTER JOIN clause.

What is outer join explain its types with example?

Outer joins are joins that return matched values and unmatched values from either or both tables. There are a few types of outer joins: LEFT JOIN returns only unmatched rows from the left table, as well as matched rows in both tables.

What is an outer join particularly useful for?

OUTER JOIN is used to retrieve all records from tables, even for those records with no matching value in the other table based on the JOIN condition. In such cases, it returns NULL as the value for the missing columns.


2 Answers

In the Northwind database on the Customers and Orders table.

Doing an inner join will only give you customers that have placed orders.

Doing an outer join will get all customers and orders for customers that have placed orders.

like image 81
Raj Kaimal Avatar answered Sep 19 '22 12:09

Raj Kaimal


To add to Robin Day's answer, you can also use a Left Outer Join to grab only customers who have NOT placed orders by checking for NULL.


SELECT *
FROM  Customer
  LEFT OUTER JOIN Order 
    ON Customer.CustomerId = Order.CustomerId
WHERE Order.CustomerId IS NULL
like image 25
CTDev Avatar answered Sep 22 '22 12:09

CTDev