Orderid Customerid Employeeid Orderdate: Joins
Orderid Customerid Employeeid Orderdate: Joins
ORDERS TABLE
O111 3 12 2021-02-18
O222 2 13 2021-02-19
O333 70 11 2021-02-20
CUSTOMERS TABLE
1 Anthony CBE
2 Balan CHENNAI
3 Ravi CHENNAI
JOIN
OLD VERSION
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders , Customers
WHERE Orders.CustomerID = Customers.CustomerID;
OrderID CustomerName
O111 Ravi
O222 Balan
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long
as there is a match between the columns. If there are records in the
"Orders" table that do not have matches in "Customers", these orders will
not be shown!
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
CustomerName OrderID
Anthony Null
Balan O222
Ravi O333
The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders)
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
11 Sharma Nina
12 Rajesh Sathish
13 Mehta Sanket
14 Khan Zara
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
CustomerName OrderID
Anthony Null
Balan O222
Ravi 0111
Null 0333
SQL Self JOIN
A self JOIN is a regular join, but the table is joined
with itself.
Example
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
Business problem
Example scenario
ABC Ltd. company launched a new campaign for the New Year and made different offers to
its online customers. As a result of their campaign, they succeeded in converting some offers
to sales. In the following examples, we will uncover the new year campaign data details of
the ABC company.
The company stores these campaign data details in the following tables.
Business problem: Which customers were interested in this New Year campaign?
In order to answer this question, we need to find out the matched rows for all the tables
because some customers did not receive an email offer, and some offers could not be
converted into a sale. The following Venn diagram will help us to figure out the matched
rows which we need. In short, the result of this query should be the intersecting rows of all
tables in the query. The grey-colored area specifies these rows in the Venn diagram: