Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Schema is fixed:
attribute names, atomic types
students(name text, gpa float, dept text)
R & G - Chapter 5
SELECT DISTINCT
ORDER BY
ORDER BY
Obviously must refer to columns in the output
Note the AS clause for naming output columns!
AGGREGATES
GROUP BY
HAVING
SELECT
FROM
WHERE
GROUP
HAVING
ORDER
Example Database
Two sublanguages:
Sailors
Boats
sid
sname rating
age
bid
bname
color
Fred
22
101
Nina
red
Jim
39
102
Pinta
blue
Nancy
27
103
Santa Maria
red
Reserves
SQL DDL
bid
day
102
9/12/2015
102
9/13/2015
sid
sname
rating
age
Fred
22
Jim
39
Nancy
27
bid
bname
color
101
Nina
red
102
Pinta
blue
103
Santa Maria
red
SELECT S.sname
FROM
Sailors AS S, Reserves AS R
WHERE S.sid=R.sid AND R.bid=102
Reserves
Sailors
sid
bid
day
bid
day
Fred
22
102
9/12
102
9/12
Jim
39
102
9/13
102
9/13
Nancy
27
SELECT
[DISTINCT]
Eliminate
duplicates
Apply selections
(eliminate rows)
WHERE
HAVING
Eliminate
groups
Relation
cross-product
FROM
GROUP BY
sid
sname rating
age
SELECT
[DISTINCT] target-list
FROM
relation-list
WHERE
qualification
GROUP BY grouping-list
HAVING group-qualification
Project away columns
(just keep those used in
SELECT, GROUP BY,
HAVING)
sid
Form groups
& aggregate
FROM
WHERE
relation-list
qualification
Sailors
Arithmetic Expressions
... or:
SELECT R.sid
FROM
Boats B, Reserves R
WHERE R.bid=B.bid AND
B.color=red'
UNION
SELECT R.sid
FROM
Boats B, Reserves R
WHERE R.bid=B.bid AND B.color='green'
sid
sname rating
age
Fred
22
Jim
39
Nancy
27
String Comparisons
SELECT S.sname
FROM
Sailors S
WHERE S.sname LIKE 'B_%B'
SELECT R.sid
FROM
Boats B,Reserves R
WHERE R.bid=B.bid AND
(B.color='red' AND B.color='green')
Nested Queries: IN
Names of sailors whove reserved boat #102:
SELECT S.sid
FROM
Sailors S
EXCEPT
SELECT S.sid
FROM
Sailors S, Reserves R
WHERE S.sid=R.sid
SELECT S.sname
FROM
Sailors S
WHERE S.sid IN
(SELECT R.sid
FROM
Reserves R
WHERE R.bid=102)
SELECT S.sname
FROM
Sailors S
WHERE EXISTS
(SELECT *
FROM Reserves R
WHERE R.bid=102 AND S.sid=R.sid)
More on Set-Comparison
Operators
weve seen: IN, EXISTS
can also have: NOT IN, NOT EXISTS
other forms: op ANY, op ALL
Find sailors whose rating is greater than that of some
sailor called Fred:
SELECT *
FROM
Sailors S
WHERE S.rating > ANY
(SELECT S2.rating
FROM Sailors S2
WHERE S2.sname='Fred')
A Tough One
Find sailors whove reserved all boats.
SELECT S.sname
FROM Sailors S
WHERE NOT EXISTS ( SELECT B.bid
FROM Boats B
there is no boat B
without ...
WHERE R.bid=B.bid
AND R.sid=S.sid ))
ARGMAX?
Null Values
SELECT *
FROM
Sailors S
WHERE S.rating =
(SELECT MAX(S2.rating)
FROM Sailors S2)
SELECT *
FROM
Sailors S
ORDER BY rating DESC
LIMIT 1;
The presence of null complicates many issues. E.g.:
Special syntax IS NULL and IS NOT NULL
Assume rating = NULL. Consider predicate rating>8.
True? False? (answer is always false)
What about AND, OR and NOT connectives?
SUM?