Review: SQL: The Query Language
Review: SQL: The Query Language
Reserves
sid bid day
1 102 9/12
2 102 9/13
Sailors
Review: SQL DDL The SQL DML sid sname rating age
sid sname rating age 1 Fred 7 22
CREATE TABLE Sailors ( 1 Fred 7 22
sid INTEGER, 2 Jim 2 39
sname CHAR(20), 2 Jim 2 39
3 Nancy 8 27
rating INTEGER, 3 Nancy 8 27
age REAL,
PRIMARY KEY sid); • Find all 18-year-old sailors:
bid bname color
CREATE TABLE Boats (
bid INTEGER, 101 Nina red
bname CHAR (20), 102 Pinta blue
SELECT * SELECT *
color CHAR(10)
PRIMARY KEY bid); 103 Santa Maria red FROM Sailors S FROM Sailors
WHERE S.age=18 WHERE age=18
CREATE TABLE Reserves (
sid INTEGER,
sid bid day
bid INTEGER,
day DATE, • To find just names and ratings, replace the first line:
1 102 9/12
PRIMARY KEY (sid, bid, date),
FOREIGN KEY sid REFERENCES Sailors, 2 102 9/13
FOREIGN KEY bid REFERENCES Boats); SELECT S.sname, S.rating
Query Semantics SELECT [DISTINCT] target-list Find sailors who’ve reserved at least one
relation-list
FROM
boat
WHERE qualification
SELECT S.sname
FROM Sailors S
WHERE S.sname LIKE ‘B_%B’ Why are Databases useful?
Here’s why
`_’ stands for any one character and `%’ stands for 0 or
more arbitrary characters.
Yes, every other language in the world uses Perl-like regular expressions.
In fact, PostgreSQL supports this with substring(), but this is not
standard or portable.
Find sid’s of sailors who’ve reserved a red or a green boat Find sid’s of sailors who’ve reserved a red and a green
boat
SELECT R.sid
FROM Boats B, Reserves R
WHERE R.bid=B.bid AND
(B.color=‘red’ OR SELECT R.sid
B.color=‘green’) FROM Boats B,Reserves R
... or: WHERE R.bid=B.bid AND
SELECT R.sid (B.color=‘red’ AND B.color=‘green’)
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’
Find sid’s of sailors who’ve reserved a red and a green Find sid’s of sailors who’ve reserved a red and a green
boat boat
Find sid’s of sailors who have not reserved a boat Nested Queries: IN
SELECT S.sname
• Find sailors whose rating is greater than that of FROM Sailors S Sailors S such that ...
some sailor called Horatio: WHERE NOT EXISTS ( SELECT B.bid
there is no boat B without
FROM Boats B ...
SELECT *
WHERE NOT EXISTS ( SELECT R.bid
FROM Sailors S
a Reserves tuple showing S reserved B FROM Reserves R
WHERE S.rating > ANY
WHERE R.bid=B.bid
(SELECT S2.rating
AND R.sid=S.sid))
FROM Sailors S2
WHERE S2.sname=‘Horatio’)
Summary