Professional Documents
Culture Documents
Part 5 - Joining Tables - Inner Join
Part 5 - Joining Tables - Inner Join
Part 5 - Joining Tables - Inner Join
Data
Le Duy Dung (Andrew)
SQL – Part 5
Joining Tables – Inner Join
S Q L Art Course Database Example
• The FROM clause has two tables, that are being joined in this SELECT
statement.
SELECT ItemDescription, ItemCost, CompanyName
• The tables are correctly joined with a WHERE clause that instructs
the DBMS to match VendorID in the ITEM table with VendorID in the
VENDOR table.
• The WHERE clause acts as a filter to include only the rows that match
the join condition.
• Without the WHERE clause, every row in the first table will be paired
with every row of second table. (Try this yourself!)
Inner Joins
• The example join earlier is called an equijoin- a join based on the
testing of equality between two tables. This kind of join also called an
inner join.
• In fact, you may use a slightly different syntax for these joins,
specifying the type of join explicitly.
<Example>
SELECT ItemDescription, ItemCost, CompanyName
FROM ITEM INNER JOIN VENDOR
ON Item.VendorID = Vendor.VendorID;
Joining multiple tables
• SQL imposes no limit to the number of tables that may be joined in
a SELECT statement.
• The basic rules for creating the join remain the same. First, list all the
tables, and then define the relationship between each.
<Example>
SELECT SaleID, Customer.FirstName AS CustFirstName ,
Employee .FirstName AS EmpFirstName , Total
FROM SALE, CUSTOMER, EMPLOYEE
WHERE SALE.CustomerID = CUSTOMER.CustomerID
AND SALE.EmployeeID = EMPLOYEE.EmployeeID
AND Total > 1000;
Joining multiple tables
• Remember subqueries?
<Example>
SELECT * FROM ITEM
WHERE ItemID IN (SELECT ItemID
FROM SALE_ITEM
WHERE SaleID IN (SELECT SaleID
FROM SALE
WHERE EmployeeID = 2));
Can you use join SQL quer y to get the same results?
Creating advanced joins
• Using table aliases
SELECT ItemDescription, ItemCost, VendorID
FROM ITEM as I, SALE as S, SALE_ITEM as SI
WHERE S.EmployeeID = 2 AND S.SaleID = SI.SaleID AND SI.ItemID = I.ItemID;
Using subqueries
SELECT CustomerID, LastName, FirstName, City
FROM CUSTOMER
WHERE City in (SELECT City FROM CUSTOMER
WHERE Phone = ‘206-524-6877’);
Creating advanced joins
• Self Join
Let’s imagine you want to send an email to all customers who are from the same city
as the customer with the phone number is 206-524-6877.
Using subqueries
SELECT CustomerID, LastName, FirstName, City
FROM CUSTOMER
WHERE City in (SELECT City FROM CUSTOMER
WHERE Phone = ‘206-524-6877’);
Creating advanced joins
• Self Join
Let’s imagine you want to send an email to all customers who are from the same city
as the customer with the phone number is 206-524-6877.