Professional Documents
Culture Documents
Example
tables
Slumlords
ID
1
2
3
Name
John Sleeze
Jenny Doohickey
Nicki Minaj
Slums
ID
1
2
3
4
Address
1355 Pearl Street
1500 East Colfax
2323 Federal
2982 Kais Rd.
SlumlordID
1
1
3
Joins
Three types:
Inner
Both sides have to match
Otherwise, no rows returned
Left Outer
Show everything thats on left, and
leave right side null if nothing there
Full Outer
Show everything on the left AND on
the right, fill in with nulls if nothing
is there.
Structure of Joins
INNER JOIN:
SELECT fields
FROM table1
INNER JOIN table2
ON table1.id = table2.id
SELECT fields
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT
RIGHT
SELECT fields FROM table1 FULL OUTER JOIN table2 ON table1.id = table2.id
Inner Join
Slumlords
ID
1
2
3
Name
John Sleeze
Jenny Doohickey
Nicki Minaj
Slums
ID
1
2
3
4
Address
1355 Pearl Street
1500 East Colfax
2323 Federal
2982 Kais Rd.
SlumlordID
1
1
3
Results
ID
1
1
3
Name
John Sleeze
John Sleeze
Nicki Minaj
Address
1355 Pearl Street
ID
1
2
3
Name
John Sleeze
Jenny Doohickey
Nicki Minaj
Slums
ID
1
2
3
4
Address
1355 Pearl Street
1500 East Colfax
2323 Federal
2982 Kais Rd.
ID
1
1
2
3
Name
John Sleeze
John Sleeze
Jenny Doohickey
Nicki Minaj
SlumlordID
1
1
3
Address
1355 Pearl Street
ID
1
2
3
Name
John Sleeze
Jenny Doohickey
Nicki Minaj
Slums
ID
1
2
3
4
Address
1355 Pearl Street
1500 East Colfax
2323 Federal
2982 Kais Rd.
ID Name
1 John Sleeze
1 John Sleeze
2 Jenny Doohickey
3 Nicki Minaj
<> <NULL>
SlumlordID
1
1
3
Address
1355 Pearl Street
Northwind example
Question: Are customers shipping to their billing address? If not, these may
be gifts. Join the customers and orders tables.
Try this1
Nowhow do you simplify the previous
query so that you do not get duplicate
rows?
Try this 2
Who ordered a specific type of product?
Create a query where you can easily
change the type of product youre looking
for:
Chai
Tofu
Pavlova
Answer Page
1:
select distinct orders.customerid, customers.companyname,
orders.shipname
from orders
inner join customers
on orders.customerid = customers.customerid
WHERE orders.shipname <> customers.companyname
2:
SELECT orders.customerid, customers.companyname
FROM orders
inner join [order details]
ON orders.orderid = [order details].orderid
inner join products
ON [order details].productid = products.productid
inner join customers
ON customers.customerid = orders.customerid
WHERE products.productname = 'chai'