sql basics joins
TRANSCRIPT
-
7/31/2019 SQL Basics Joins
1/35
SQL II
-
7/31/2019 SQL Basics Joins
2/35
SQL Queries (so far)
Basic SQL Queries
SELECT-FROM-WHERE
Expressions and strings in SELECT and WHERE
UNION-type Queries Union, intersect, except queries
They do duplicate elimination by default!
You need to use ALL, eg. UNION ALL for retaining the duplicates.
Nested Queries
Allow for very complex queries
-
7/31/2019 SQL Basics Joins
3/35
sid sname rating age
22 Dustin 7 45.0
31 Lubber 8 55.595 Bob 3 63.5
bid bname color
101 Interlake blue102 Interlake red
103 Clipper green
104 Marine red
sid bid day
22 101 10/10/96
95 103 11/12/96
Reserves
Sailors
Boats
We will use theseinstances ofrelations in our
examples.
-
7/31/2019 SQL Basics Joins
4/35
Example Schemas
-
7/31/2019 SQL Basics Joins
5/35
INTERSECT
SELECT S.sidFROM Sailors S, Boats B,
Reserves RWHERE S.sid=R.sid
AND R.bid=B.bidAND B.color=redINTERSECTSELECT S.sidFROM Sailors S, Boats B,
Reserves RWHERE S.sid=R.sid
AND R.bid=B.bidAND B.color=green
Key field!
What if we used snameinstead of sid?
-
7/31/2019 SQL Basics Joins
6/35
Find sids of sailors whove reserved a red but did not reserve agreen boat
SELECT S.sidFROM Sailors S, Boats B,
Reserves RWHERE S.sid=R.sid
AND R.bid=B.bidAND B.color=redEXCEPTSELECT S.sidFROM Sailors S, Boats B,
Reserves RWHERE S.sid=R.sid
AND R.bid=B.bidAND B.color=green
Duplicate eliminationIs important here!
-
7/31/2019 SQL Basics Joins
7/35
Powerful feature of SQL: WHERE clause can itself contain an
SQL query!
Actually, so can FROM and HAVING clauses.
To find sailors whove notreserved #103, use NOT IN.
To understand semantics of nested queries:
think of a nested loopsevaluation: For each Sailors tuple, check thequalification by computing the subquery.
Nested Queries
SELECT S.sname
FROM Sailors SWHERE S.sid IN (SELECT R.sid
FROM Reserves RWHERE R.bid=103)
Names of sailors whove reserved boat #103:
-
7/31/2019 SQL Basics Joins
8/35
More on Set-Comparison Operators
Weve already seen IN, EXISTS and UNIQUE. Can also use NOT
IN, NOT EXISTS and NOT UNIQUE.
Also available: opANY, opALL
Find sailors whose rating is greater than that of some sailor
called Horatio:
SELECT *FROM Sailors S
WHERE S.rating > ANY (SELECT S2.ratingFROM Sailors S2WHERE S2.sname=Horatio)
-
7/31/2019 SQL Basics Joins
9/35
Basic SQL Queries - Summary
An advantage of the relational model is its
well-defined query semantics.
SQL provides functionality close to that ofthe basic relational model.
some differences in duplicate handling, null values, set operators,etc.
Typically, many ways to write a query
the system is responsible for figuring a fast way to actually
execute a query regardless of how it is written.
-
7/31/2019 SQL Basics Joins
10/35
Aggregate Operators
COUNT (*)COUNT ( [DISTINCT] A)SUM ( [DISTINCT] A)AVG ( [DISTINCT] A)MAX (A)MIN (A)
SELECT AVG ( DISTINCT S.age)FROM Sailors S
WHERE S.rating=10
SELECT S.snameFROM Sailors SWHERE S.rating= (SELECT MAX(S2.rating)
FROM Sailors S2)
single column
-
7/31/2019 SQL Basics Joins
11/35
Find name and age of the oldest sailor(s)
The first query is illegal in
SQL!
SELECT S.sname, MAX (S.age)FROM Sailors S
SELECT S.sname, S.ageFROM Sailors SWHERE S.age =
(SELECT MAX (S2.age)FROM Sailors S2)
SELECT S.sname, S.ageFROM Sailors SWHERE (SELECT MAX (S2.age)
FROM Sailors S2)
= S.age
Third query equivalent tosecond query allowed inSQL/92 standard, but notsupported in some systems.
-
7/31/2019 SQL Basics Joins
12/35
Queries With GROUP BY
Thetarget-listcontains (i) list of column names &
(ii)terms with aggregate operations (e.g., MIN (S.age)).
column name list (i)can contain only attributes from thegrouping-list.
SELECT [DISTINCT] target-list
FROM relation-list[WHERE qualification]GROUP BYgrouping-list
Therefore we use a new operator in SQL, theGROUP BY clause
-
7/31/2019 SQL Basics Joins
13/35
Group By Examples
SELECT S.rating, AVG (S.age)FROM Sailors SGROUP BY S.rating
For each rating, find the average age of the sailors
For each rating find the age of the youngestsailor with age 18
SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.rating
-
7/31/2019 SQL Basics Joins
14/35
Conceptual Evaluation
The cross-product ofrelation-listis computed, tuples that failqualificationare discarded, `unnecessary fields are deleted,and the remaining tuples are partitioned into groups by the
value of attributes in grouping-list.
One answer tuple is generated per qualifying group.
-
7/31/2019 SQL Basics Joins
15/35
SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18
GROUP BY S.rating
sid sname rating age
22 dustin 7 45.0
31 lubber 8 55.5
71 zorba 10 16.064 horatio 7 35.0
29 brutus 1 33.0
58 rusty 10 35.0
1. Form cross product
rating age
1 33.0
7 45.07 35.0
8 55.5
10 35.0
2. Delete unneeded columns,rows; form groups
3. PerformAggregation
ating age
1 33.0
7 35.08 55.0
10 35.0
Answer Table
-
7/31/2019 SQL Basics Joins
16/35
Find the number of reservations foreach red boat.
Grouping over a join of two relations.
SELECT B.bid, COUNT(*)AS numresFROM Boats B, Reserves R
WHERE R.bid=B.bidAND B.color=red
GROUP BY B.bid
-
7/31/2019 SQL Basics Joins
17/35
SELECT B.bid, COUNT (*) AS scountFROM Boats B, Reserves RWHERE R.bid=B.bid ANDB.color=redGROUP BY B.bid
1
b.bid b.color r.bid
101 blue 101
102 red 101
103 green 101104 red 101
101 blue 102
102 red 102
103 green 102
104 red 102
b.bid b.color r.bid
102 red 102
2
b.bid scount
102 1answer
-
7/31/2019 SQL Basics Joins
18/35
Queries With GROUP BY and HAVING
Use the HAVING clause with the GROUP BY clause to
restrict which group-rows are returned in the result set
SELECT [DISTINCT] target-listFROM relation-listWHERE qualification
GROUP BY grouping-listHAVING group-qualification
-
7/31/2019 SQL Basics Joins
19/35
Conceptual Evaluation
Form groups as before.
The group-qualificationis then applied toeliminate some groups.
Expressions in group-qualificationmust have a single value per group!
That is, attributes in group-qualificationmust be arguments of anaggregate op or must also appear in the grouping-list. (SQL does notexploit primary key semantics here!)
One answer tuple is generated per qualifyinggroup.
-
7/31/2019 SQL Basics Joins
20/35
Find the age of the youngest sailor with age 18,for each rating with at least 2 such sailors
SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.rating
HAVING COUNT (*) > 1
rating
7 35.0
Answer relation
rating age
1 33.0
7 45.0
7 35.0
8 55.5
10 35.0
2
rating m-age count
1 33.0 17 35.0 2
8 55.0 1
10 35.0 13
sid sname rating age22 Dustin 7 45.0
31 lubber 8 55.5
71 zorba 10 16.0
64 horatio 7 35.029 brutus 1 33.0
58 rusty 10 35.0
-
7/31/2019 SQL Basics Joins
21/35
SELECT S.snameFROM Sailors SWHERE NOT EXISTS (SELECT B.bid
FROM Boats B
WHERE NOT EXISTS (SELECT R.bidFROM Reserves RWHERE R.bid=B.bid
AND R.sid=S.sid))
Sailors S such that ...
there is no boat B without...
a Reserves tuple showing S reserved B
Find sailors whove reserved all boats.
-
7/31/2019 SQL Basics Joins
22/35
Can you do this using Group By and
Having?
SELECT S.name
FROM Sailors S, reserves RWHERE S.sid = R.sidGROUP BY S.name, S.sidHAVING
COUNT(DISTINCT R.bid) =( Select COUNT (*) FROM Boats)
Find sailors whove reserved all boats.
Note: must have both sid and name in the GROUP BY
clause. Why?
-
7/31/2019 SQL Basics Joins
23/35
SELECT S.name, S.sid
FROM Sailors S, reserves R
WHERE S.sid = r.sidGROUP BY S.name, S.sid
HAVING
COUNT(DISTINCT R.bid) =
Select COUNT (*) FROM Boats
s.name s.sid r.sid r.bid
Dustin 22 22 101
Lubber 31 22 101
Bob 95 22 101Dustin 22 95 102
Lubber 31 95 102
Bob 95 95 102
s.name s.sid bcount
Dustin 22 1
Bob 95 1
bid bname color
101 Interlake blue
102 Interlake red103 Clipper green
104 Marine red
Count (*) from boats = 4
Apply having clause to groups
s.name s.sid
-
7/31/2019 SQL Basics Joins
24/35
Null Values
Field values in a tuple are sometimes unknown(e.g., a ratinghas not been assigned) orinapplicable(e.g., no spousesname).
SQL provides a special value nullfor such situations.
The presence ofnullcomplicates many issues. E.g.: Special operators needed to check if value is/is not null.
Is rating>8true or false when ratingis equal to null? What aboutAND, OR andNOT connectives?
We need a 3-valued logic (true, false and unknown).
Meaning of constructs must be defined carefully. (e.g., WHERE clauseeliminates rows that dont evaluate to true.)
New operators (in particular, outer joins) possible/needed.
-
7/31/2019 SQL Basics Joins
25/35
Joins
Explicit join semantics needed unless it is an INNER join(INNER is default)
SELECT (column_list)FROM table_name
[INNER | {LEFT |RIGHT | FULL } OUTER] JOIN table_nameON qualification_list
WHERE
-
7/31/2019 SQL Basics Joins
26/35
Inner Join
Only the rows that match the search conditions are returned.
SELECT s.sid, s.name, r.bid
FROM Sailors s INNER JOIN Reserves r
ON s.sid = r.sidReturns only those sailors who have reserved boats
SQL-92 also allows:
SELECT s.sid, s.name, r.bid
FROM Sailors s NATURAL JOIN Reserves r
NATURAL means equi-join for each pair of attributes with thesame name
-
7/31/2019 SQL Basics Joins
27/35
SELECT s.sid, s.name, r.bidFROM Sailors s INNER JOIN Reserves r
ON s.sid = r.sid
s.sid s.name r.bid22 Dustin 101
95 Bob 103
sid sname rating age
22 Dustin 7 45.0
31 Lubber 8 55.595 Bob 3 63.5
sid bid day
22 101 10/10/96
95 103 11/12/96
-
7/31/2019 SQL Basics Joins
28/35
Left Outer Join
Left Outer Join returns all matched rows, plus all
unmatched rows from the table on the left of the join
clause
(use nulls in fields of non-matching tuples)
SELECT s.sid, s.name, r.bid
FROM Sailors s LEFT OUTER JOIN Reserves r
ON s.sid = r.sid
Returns all sailors & information on whether they have
reserved boats
-
7/31/2019 SQL Basics Joins
29/35
SELECT s.sid, s.name, r.bidFROM Sailors s LEFT OUTER JOIN Reserves r
ON s.sid = r.sid
s.sid s.name r.bid22 Dustin 101
95 Bob 103
31 Lubber NULL
sid sname rating age
22 Dustin 7 45.0
31 Lubber 8 55.595 Bob 3 63.5
sid bid day
22 101 10/10/96
95 103 11/12/96
-
7/31/2019 SQL Basics Joins
30/35
Right Outer Join
Right Outer Join returns all matched rows, plus all
unmatched rows from the table on the right of the join
clause
SELECT r.sid, b.bid, b.name
FROM Reserves r RIGHT OUTER JOIN Boats b
ON r.bid = b.bid
Returns all boats & information on which ones are
reserved.
-
7/31/2019 SQL Basics Joins
31/35
SELECT r.sid, b.bid, b.nameFROM Reserves r RIGHT OUTER JOIN Boats b
ON r.bid = b.bid
r.sid b.bid b.name
22 101 Interlake102 Interlake
95 103 Clipper
NULL 104 Marine
sid bid day
22 101 10/10/96
95 103 11/12/96
bid bname color
101 Interlake blue
102 Interlake red
103 Clipper green104 Marine red
-
7/31/2019 SQL Basics Joins
32/35
Full Outer Join
Full Outer Join returns all (matched or unmatched) rows
from the tables on both sides of the join clause
SELECT r.sid, b.bid, b.nameFROM Reserves r FULL OUTER JOIN Boats b
ON r.bid = b.bid
Returns all boats & all information on reservations
-
7/31/2019 SQL Basics Joins
33/35
SELECT r.sid, b.bid, b.name
FROM Reserves r FULL OUTER JOIN Boats bON r.bid = b.bid
r.sid b.bid b.name
22 101 Interlake
102 Interlake
95 103 Clipper 104 Marine
Note: in this case it is the same as the ROJ becausebid is a foreign key in reserves, so all reservations must
have a corresponding tuple in boats.
sid bid day22 101 10/10/96
95 103 11/12/96
bid bname color
101 Interlake blue102 Interlake red
103 Clipper green
104 Marine red
-
7/31/2019 SQL Basics Joins
34/35
Views
CREATE VIEW view_nameAS select_statement
Makes development simplerOften used for securityNot instantiated - makes updates tricky
CREATE VIEW Reds
AS SELECT B.bid, COUNT (*) AS scountFROM Boats B, Reserves RWHERE R.bid=B.bid AND B.color=redGROUP BY B.bid
-
7/31/2019 SQL Basics Joins
35/35
CREATE VIEW Reds
AS SELECT B.bid, COUNT (*) AS scountFROM Boats B, Reserves R
WHERE R.bid=B.bid AND B.color=redGROUP BY B.bid
b.bid scount102 1
Reds