Lecture 6 SQL Part 2
Lecture 6 SQL Part 2
Recap: Lecture 3
• SQL Data types
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
1
International University, VNU-HCMC
Acknowledgement
Today’s topic
• More SQL
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
– Extended algebra
– Semantic
– Joins
– Group by and aggregates
– Nested queries
2
International University, VNU-HCMC
τ = sort tuples.
γ = grouping and aggregation.
Outerjoin: avoids “dangling tuples” =
tuples that do not join with anything.
Duplicate Elimination
• R1 := δ(R2).
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
3
International University, VNU-HCMC
R= (A B)
1 2
3 4
1 2
δ(R) = A B
1 2
3 4
Sorting
• R1 := τL (R2).
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
4
International University, VNU-HCMC
Example: Sorting
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
R= (A B)
1 2
3 4
5 2
Aggregation Operators
• Aggregation operators are not operators of
relational algebra.
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
5
International University, VNU-HCMC
Example: Aggregation
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
R= (A B)
1 3
3 4
3 2
SUM(A) = 7
COUNT(A) = 3
MAX(B) = 4
AVG(B) = 3
Grouping Operator
• R1 := γL (R2). L is a list of elements
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
6
International University, VNU-HCMC
Applying γL(R)
• Group R according to all the grouping
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
attributes on list L.
– That is: form one group for each distinct list
of values for those attributes in R.
• Within each group, compute AGG(A) for
each aggregation on list L.
• Result has one tuple for each group:
1. The grouping attributes and
2. Their group’s aggregations.
Example: Grouping/Aggregation
R= (A B C)
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
1 2 3 Then, average C
4 5 6 within groups:
1 2 5
A B X
γA,B,AVG(C)->X (R) = ?? 1 2 4
First, group R by A and B : 4 5 6
A B C
1 2 3
1 2 5
4 5 6
7
International University, VNU-HCMC
Outerjoin
• Suppose we join R ⋈C S.
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Example: Outerjoin
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
R= (A B) S= (B C)
1 2 2 3
4 5 6 7
8
International University, VNU-HCMC
WHERE <qualification>
9
International University, VNU-HCMC
SQL IN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
10
International University, VNU-HCMC
FROM table_name
WHERE CONDITION;
11
International University, VNU-HCMC
WHERE <qualification>
12
International University, VNU-HCMC
13
International University, VNU-HCMC
A Note on “Alias”
• You can rename a table or a column temporarily by
giving another name known as Alias
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Reserves
sid bid day
22 101 10/10/19
58 103 11/12/19
14
International University, VNU-HCMC
15
International University, VNU-HCMC
Example
• To find all 18 year old students, we can write:
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
all attributes
•To find just names and logins, replace the first line:
16
International University, VNU-HCMC
Joins
sid sname rating age
• Condition/Theta-Join 22 dustin 7 45
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
31 lubber 8 55
• Equi-Join
58 rusty 10 35
• Natural-Join
• (Left/Right/Full) Outer-
Join sid bid day
22 101 10/10/19
58 103 11/12/19
17
International University, VNU-HCMC
Condition/Theta Join
sid sname rating age
SELECT *
FROM Sailors S, Reserves R 22 dustin 7 45
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
sid sname rating age sid bid day sid bid day
22 dustin 7 45 22 101 10/10/19 22 101 10/10/19
22 dustin 7 45 58 103 11/12/19 58 103 11/12/19
31 lubber 8 55 22 101 10/10/19
31 lubber 8 55 58 103 11/12/19
58 rusty 10 35 22 101 10/10/19
58 rusty 10 35 58 103 11/12/19
Equi Join
sid sname rating age
SELECT *
FROM Sailors S, Reserves R 22 dustin 7 45
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
sid sname rating age sid bid Day sid bid day
22 dustin 7 45 22 101 10/10/19 22 101 10/10/19
22 dustin 7 45 58 103 11/12/19 58 103 11/12/19
31 lubber 8 55 22 101 10/10/19
31 lubber 8 55 58 103 11/12/19
58 rusty 10 35 22 101 10/10/19
58 rusty 10 35 58 103 11/12/19
18
International University, VNU-HCMC
Natural Join
sid sname rating age
SELECT *
22 dustin 7 45
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Outer Join
sid sname rating age
SELECT S.sid, R. bid
22 dustin 7 45
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
19
International University, VNU-HCMC
FROM Sailors S
WHERE S.sname LIKE ‘B_%B’
Like Operator
There are two wildcards often used in
conjunction with the LIKE operator:
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
20
International University, VNU-HCMC
Example
• SELECT * FROM Customers
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
UNION Clause/Operator
The SQL UNION clause/operator is used to combine the
results of two or more SELECT statements without
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
21
International University, VNU-HCMC
Syntax of a UNION
SELECT column1 [, column2 ]
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
INTERSECT Clause/Operator
INTERSECT
22
International University, VNU-HCMC
EXCEPT Clause/Operator
The SQL EXCEPT returns only rows, which are
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
23
International University, VNU-HCMC
apple apple
apple orange
orange orange
24
International University, VNU-HCMC Sailors (sid,sname,rating,age)
Reserves(sid, bid, day)
INTERSECT Clause/Operator Boats(bid, bname, color)
SELECT S.sid
• INTERSECT: Can be used to
FROM Sailors S, Boats B, Reserves R
compute the intersection of
any two union-compatible WHERE S.sid=R.sid AND R.bid=B.bid
sets of tuples. AND B.color=‘red’
– Included in the SQL/92 INTERSECT
SELECT S.sid
standard, but some
FROM Sailors S, Boats B, Reserves R
systems don’t support it
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘green’
Duke CS, Fall 2021 50
25
International University, VNU-HCMC
Nested Queries
A Subquery or Inner query or a Nested query is a
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
26
International University, VNU-HCMC
In syntax
SELECT column_name(s)
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
FROM table_name
WHERE column_name IN (value1, value2, ...);
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Exists syntax
SELECT column_name(s)
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE
condition);
27
International University, VNU-HCMC
9
IN subqueries
User(uid, name, age, pop)
• 𝑥 IN (𝑠𝑢𝑏𝑞𝑢𝑒𝑟𝑦) checks if 𝑥 is in the result of
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
𝑠𝑢𝑏𝑞𝑢𝑒𝑟𝑦
• Example: users (all columns) at the same age as
(some) Long
Let’s first try without sub-queries
• SELECT * FROM
You can use NOT IN too
User
WHERE age IN (SELECT age
FROM User
WHERE name = ‘Long');
EXISTS subqueries
User(uid, name, age, pop)
is non-empty
• Example: users at the same age as (some) Bart
• SELECT *
FROM User AS u
WHERE EXISTS (SELECT * FROM User
WHERE name = 'Bart'
AND age = u.age);
28
International University, VNU-HCMC
SELECT S.sname
FROM Sailors S
WHERE EXISTS (SELECT *
FROM Reserves R
WHERE R.bid=103 AND S.sid=R.sid)
29
International University, VNU-HCMC
SELECT S.sname
FROM Sailors S
WHERE UNIQUE (SELECT R.bid
FROM Reserves R
WHERE R.bid=103 AND S.sid=R.sid)
Another example
User(uid, name, pop)
Member(uid, gid)
• SELECT * FROM User u Group(gid, name)
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
WHERE EXISTS
(SELECT * FROM Member m
WHERE m.uid = u.uid
AND EXISTS
(SELECT * FROM Member n
WHERE n.uid = u.uid
AND n.gid <> m.gid));
30
International University, VNU-HCMC
• Can also use NOT IN, NOT EXISTS and NOT UNIQUE.
• Also available: op ANY, op ALL, op IN
– where op : >, <, =, <=, >=
• Find sailors whose rating is greater than that of some
sailor called Horatio
SELECT *
– similarly ALL FROM Sailors S
WHERE S.rating > ANY (SELECT S2.rating
FROM Sailors S2
WHERE S2.sname=‘Horatio’)
Aggregate Operators
COUNT (*)
Check yourself: COUNT ([DISTINCT] A)
What do these queries compute?
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
SUM ([DISTINCT] A)
AVG ([DISTINCT] A)
SELECT COUNT (*) MAX (A)
FROM Sailors S MIN (A)
single column
31
International University, VNU-HCMC
(qualifying) tuples
– Sometimes, we want to apply them to each of several groups of
tuples
• Consider: Find the age of the youngest sailor for each
rating level
– In general, we don’t know how many rating levels exist, and
what the rating values for these levels are!
– Suppose we know that rating values go from 1 to 10; we can write
10 queries that look like this (need to replace i by num):
32
International University, VNU-HCMC
Conceptual Evaluation
• The cross-product of relation-list is computed
• Tuples that fail qualification are discarded
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Sailors instance:
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
33
International University, VNU-HCMC
Find age of the youngest sailor with age >= 18, for each rating with
at least 2 such sailors.
SELECT S.rating, MIN (S.age) AS minage Sailors instance:
FROM Sailors S
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
34
International University, VNU-HCMC
Find age of the youngest sailor with age >= 18, for each rating with
at least 2 such sailors. SELECT S.rating,
MIN (S.age) AS minage
Step 2: Apply WHERE clause FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
35
International University, VNU-HCMC
Find age of the youngest sailor with age >= 18, for each rating with
at least 2 such sailors. SELECT S.rating,
MIN (S.age) AS minage
Step 4: Apply HAVING clause FROM Sailors S
The group-qualification is applied to eliminate some groups WHERE S.age >= 18
GROUP BY S.rating
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
36
International University, VNU-HCMC
Top Clause
The SQL TOP clause is used to fetch a TOP N
number or X percent records from a table.
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
MySQL syntax
SELECT column_name(s)
FROM table_name
WHERE [condition]
LIMIT number;
Duke CS, Fall 2021 74
Demo database
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
37
International University, VNU-HCMC
Order by syntax
SELECT column1, column2, ...
FROM table_name
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
SELECT *
FROM Customers
ORDER BY Country;
Case syntax
CASE
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
38
International University, VNU-HCMC
Demo Database
OrderDatails table
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Case example
SELECT OrderID, Quantity,
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
CASE
WHEN Quantity > 30 THEN 'The
quantity is greater than 30'
WHEN Quantity = 30 THEN 'The
quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
39
International University, VNU-HCMC
Example
• The following SQL will order the customers
by City. However, if City is NULL, then order
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
by Country
40
International University, VNU-HCMC
WITH CLAUSE
WITH Cus_CTE (sid, sname, sage, searning)
AS
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’
AND S.sid IN (SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid
AND B2.color=‘green’)
41
International University, VNU-HCMC
Division in SQL
Find sailors who’ve reserved all boats.
• Option 1:
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
Example
• Find the names of students who’ve enrolled a
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
42
International University, VNU-HCMC
43
International University, VNU-HCMC
Find age of the youngest sailor with age >= 18, for each
rating with at least 2 sailors between 18 and 60.
44
International University, VNU-HCMC
For each red boat, find the number of
reservations for this boat
SELECT B.bid, COUNT (*) AS scount
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
45
International University, VNU-HCMC
Find age of the youngest sailor with age > 18, for
each rating with at least 2 sailors (of any age)
SELECT S.rating, MIN (S.age)
FROM Sailors S
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
SELECT S.rating
FROM Sailors S WRONG
WHERE S.age = (SELECT MIN (AVG (S2.age))
FROM Sailors S2)
• Correct solution (in SQL/92):
SELECT Temp.rating, Temp.avgage
FROM (SELECT S.rating, AVG (S.age) AS avgage
FROM Sailors S
GROUP BY S.rating) AS Temp
WHERE Temp.avgage = (SELECT MIN (Temp.avgage)
FROM Temp)
Duke CS, Fall 2021 94
46
International University, VNU-HCMC
Triggers
• Trigger: procedure that starts automatically if specified
changes occur to the DBMS
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
• Three parts:
– Event (activates the trigger)
– Condition (tests whether the triggers should run)
– Action (what happens if the trigger runs)
47
International University, VNU-HCMC
Null Values
• Field values in a tuple are sometimes
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
• Suppose X = 5
– (X < 100) AND (X >= 1) is T ∧T = T
– (X > 100) OR (X >= 1) is F ∨T = T
– (X > 100) AND (X >= 1) is F ∧T = F
– NOT(X = 5) is ¬T = F
• Intuitively,
– T = 1, F = 0
– For V1, V2 ∈{1, 0}
– V1 ∧V2 = MIN (V1, V2)
– V1 ∨V2 = MAX(V1, V2)
– ¬(V1) = 1 – V1
48
International University, VNU-HCMC
• Therefore,
– NOT UNKNOWN = UNKNOWN
– UNKNOWN OR TRUE = TRUE
– UNKNOWN AND TRUE = UNKNOWN
– UNKNOWN AND FALSE = FALSE
– UNKNOWN OR FALSE = UNKNOWN
49
International University, VNU-HCMC
– Be careful!
– “WHERE X = NULL” does not work!
– Need to write “WHERE X IS NULL”
R1
50
International University, VNU-HCMC
R2
51
International University, VNU-HCMC
52
International University, VNU-HCMC
53
International University, VNU-HCMC
VIEWS
Views, which are a type of virtual tables. Views can be
created from a single table, multiple tables or another
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
view.
VIEWS
Views can be dropped using the DROP VIEW command
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
54
International University, VNU-HCMC
UPDATING A VIEW
A view can be updated under certain conditions which are
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
given below −
§ The SELECT clause may not contain the keyword DISTINCT.
§ The SELECT clause may not contain summary functions.
§ The SELECT clause may not contain set functions.
§ The SELECT clause may not contain set operators.
§ The SELECT clause may not contain an ORDER BY clause.
§ The FROM clause may not contain multiple tables.
§ The WHERE clause may not contain subqueries.
§ The query may not contain GROUP BY or HAVING.
§ Calculated columns may not be updated.
55
International University, VNU-HCMC
Summary
• SQL has a huge number of constructs and possibilities
Assoc. Prof. Nguyen Thi Thuy Loan, PhD
56