In SQL, a RIGHT JOIN performs a join starting with the right table.
Then, any matching records from the left table will be included.
Rows without a match will have NULL column values.
List all products that have no orders.
SELECT ProductName
FROM OrderItem I
RIGHT JOIN Product P ON P.Id = I.ProductId
WHERE I.Id IS NULL
Only 1 product never sold.
ProductName |
---|
Stroopwafels |
RIGHT JOIN syntax.
SELECT column-names FROM table-name1 RIGHT JOIN table-name2 ON column-name1 = column-name2 WHERE condition
RIGHT OUTER JOIN syntax.
SELECT column-names FROM table-name1 RIGHT OUTER JOIN table-name2 ON column-name1 = column-name2 WHERE condition
RIGHT JOIN and RIGHT OUTER JOIN are the same.
The OUTER keyword is optional.
CUSTOMER |
---|
Id |
FirstName |
LastName |
City |
Country |
Phone |
ORDER |
---|
Id |
OrderDate |
OrderNumber |
CustomerId |
TotalAmount |
SELECT FirstName, LastName, City, Country, TotalAmount
FROM [Order] O
RIGHT JOIN Customer C ON O.CustomerId = C.Id
WHERE TotalAmount IS NULL
This returns customers that, when joined, have no matching order.
FirstName | LastName | City | Country | TotalAmount |
---|---|---|---|---|
Diego | Roel | Madrid | Spain | NULL |
Marie | Bertrand | Paris | France | NULL |
CUSTOMER |
---|
Id |
FirstName |
LastName |
City |
Country |
Phone |
ORDER |
---|
Id |
OrderDate |
OrderNumber |
CustomerId |
TotalAmount |
ORDERITEM |
---|
Id |
OrderId |
ProductId |
UnitPrice |
Quantity |
SELECT DISTINCT (C.Id), Firstname, LastName, COUNT(O.Id) AS Orders
FROM [Order] O
JOIN OrderItem I ON O.Id = I.OrderId AND I.ProductId = 13
RIGHT JOIN Customer C ON C.Id = O.CustomerId
GROUP BY C.Id, FirstName, LastName
ORDER BY COUNT(O.Id)
This returns all customers whether they have orders or not.
The ones with orders are checked for productId = 13.
Id | FirstName | LastName | Orders |
---|---|---|---|
1 | Maria | Anders | 0 |
3 | Antonio | Moreno | 0 |
6 | Hanna | Moos | 0 |
36 | Yoshi | Latimer | 1 |
88 | Paula | Patenta | 1 |
85 | Paul | Henriot | 1 |
11 | Victoria | Ashworth | 2 |
17 | Sven | Ottlieb | 2 |
20 | Roland | Mendel | 2 |
71 | Jose | Pavarotti | 4 |