Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL RIGHT JOIN

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.

SQL RIGHT JOIN

Example

#

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.

Result:  1 record
ProductName
Stroopwafels

Syntax

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.


More Examples

RIGHT JOIN example

CUSTOMER
Id
FirstName
LastName
City
Country
Phone
ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: List customers that have not placed orders.
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.

Result:  2 records
FirstName LastName City Country TotalAmount
Diego Roel Madrid Spain NULL
Marie Bertrand Paris France NULL

RIGHT JOIN, with a JOIN

Problem: List all customers -- with or without orders -- and a count of the orders that include a '2kg box with Konbu' (product with Id = 13). Sort the results by number of orders.
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.

Result:  91 records (all customers)
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

You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.