Lec10 2up
Lec10 2up
Part 2
CS 186, Fall 2002
Lecture 10
R & G - Chapter 5
Albert Einstien
1
Queries With GROUP BY
• To generate values for a column based on groups
of rows, use aggregate functions in SELECT
statements with the GROUP BY clause
Group By Examples
2
Conceptual Evaluation
• The cross-product of relation-list is computed, tuples
that fail qualification are discarded, `unnecessary’
fields are deleted, and the remaining tuples are
partitioned into groups by the value of attributes in
grouping-list.
3
Find the number of reservations for
each red boat.
1 2
b.bid scount
102 1
answer
4
Queries With GROUP BY and HAVING
Conceptual Evaluation
5
Find the age of the youngest sailor with age ≥
18, for each rating with at least 2 such sailors
SELECT S.sname
FROM Sailors S Sailors S such that ...
WHERE NOT EXISTS (SELECT B.bid there is no boat B without
FROM Boats B ...
WHERE NOT EXISTS (SELECT R.bid
a Reserves tuple showing S reserved B FROM Reserves R
WHERE R.bid=B.bid
AND R.sid=S.sid))
6
Find sailors who’ve reserved all boats.
• Can you do this using Group By
and Having?
SELECT S.name
FROM Sailors S, reserves R
WHERE S.sid = R.sid
GROUP BY S.name, S.sid
HAVING
COUNT(DISTINCT R.bid) =
( Select COUNT (*) FROM Boats)
Note: must have both sid and name in the GROUP BY
clause. Why?
7
INSERT
INSERT [INTO] table_name [(column_list)]
VALUES ( value_list)
8
Null Values
• Field values in a tuple are sometimes unknown (e.g., a
rating has not been assigned) or inapplicable (e.g., no
spouse’s name).
– SQL provides a special value null for such situations.
• The presence of null complicates many issues. E.g.:
– Special operators needed to check if value is/is not null.
– Is rating>8 true or false when rating is equal to null? What
about AND, OR and NOT connectives?
– We need a 3-valued logic (true, false and unknown).
– Meaning of constructs must be defined carefully. (e.g.,
WHERE clause eliminates rows that don’t evaluate to true.)
– New operators (in particular, outer joins) possible/needed.
Joins
SELECT (column_list)
FROM table_name
[INNER | {LEFT |RIGHT | FULL } OUTER] JOIN table_name
ON qualification_list
WHERE …
9
Inner Join
Only the rows that match the search conditions are
returned.
10
Left Outer Join
11
Right Outer Join
12
Full Outer Join
13
Views
b.bid scount
102 1
Reds
14