Friday, 6 October 2017

SQL RIGHT JOIN ~ niit post

  • RIGHT JOIN performs a join starting with the second (right-most) table and then any matching first (left-most) table records.
  • RIGHT JOIN and RIGHT OUTER JOIN are the same.


The SQL RIGHT JOIN syntax


The general syntax is: 

1.  SELECT column-names
2.    FROM table-name1 RIGHT JOIN table-name2 
3.      ON column-name1 = column-name2
4.   WHERE condition

The general RIGHT OUTER JOIN syntax is: 

1.  SELECT column-names
2.    FROM table-name1 RIGHT OUTER JOIN table-name2 
3.      ON column-name1 = column-name2
4.   WHERE condition



CUSTOMER
Id
FirstName
LastName
City
Country
Phone

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount


SQL RIGHT JOIN Example



Problem: List customers that have not placed orders 


1.  SELECT TotalAmount, FirstName, LastName, City, Country
2.    FROM [Order] O RIGHT JOIN Customer C
3.      ON O.CustomerId = C.Id
4.  WHERE TotalAmount IS NULL

This returns customers that, when joined, have no matching order. 

Results: 2 records 

TotalAmount
FirstName
LastName
City
Country
NULL
Diego
Roel
Madrid
Spain
NULL
Marie
Bertrand
Paris
France


No comments:

Post a Comment