Download SQL Querying: Understanding Cartesian Products, Subqueries, and Aggregate Functions - Prof and more Study notes Database Management Systems (DBMS) in PDF only on Docsity!
Winter 2003 1
Today’s Lecture
- More on SQL
- Nested Queries
- Aggregate operators and Nulls
Winter 2003 2
R ecom m en ded R eadi n g s
- Chapter 5
- http://philip.greenspun.com/sql/
- Simple queries, more complex queries
Winter 2003 3
B asi c f orm of S Q L
- We have already seen the basic form of SQL:
- relation-list : A list of relation names (possibly with a range-variable after each name). E.g., FROM Sailors s, Reserves r
- target-list: A list of attributes of relations in relation-list. * can be used to denote all attributes. E.g., SELECT s.sname, SELECT *
- qualification : Comparisons (Attr op const or Attr1 op Attr2, where op is one of <, >, =,
, , ≠ combined using AND, OR and NOT.
- DISTINCT (optional) keyword indicates that the answer should not contain duplicates. Default is that duplicates are not eliminated!
SELECT [DISTINCT] target-list
FROM relation-list
[WHERE qualification ]
Winter 2003 4
S em an ti cs of th e S Q L q uery
- Informally:
- Result1: Compute the cartesian product of all
relations in the relation list
- Result2: Apply the conditions in qualification list to
eliminate tuples from Result1 that do not satisfy the
conditions
- Result3: Retrieve only the required components from
each tuple in Result2 according to target list
- Result: Eliminate duplicate rows in Result3 if
DISTINCT keyword is present in the SELECT clause
Winter 2003 7
Expressions and Strings in the SELECT
c lau se
- General form of SELECT clause
- SELECT expr 1 AS col-name 1 , …, exprn AS col-namen
- Expr is any arithmetic or string expressions over
column names and constants
- Col-name is a new name for the corresponding output
column according to expr
Winter 2003 8
E x am p les
SELECT sid, cname, age+
FROM Customers
SELECT sid AS id, cname AS name, (age*100 – sid)/33 AS shoe-size
FROM Customers
Winter 2003 9
S tri n g m atch i n g
- Support for string matching through LIKE clause
- % denotes zero or more arbitrary characters
- _ denotes exactly one arbitrary character
- Examples
- ‘abc’ LIKE a_ _% is true
- ‘abc’ LIKE %%_c is true
- ‘abc’ LIKE a%b%_c is false
- Find the ids of all customers whose name ends with the letter ‘e’ SELECT sid FROM Customers WHERE name LIKE ‘%e’
Winter 2003 10
N ested Q ueri es
- A nested query is a query with another query embedded
in it
- Embedded query = subquery
- A subquery can in turn have subqueries
- Nested queries are convenient for computing results that
depend on some intermediate results that need to be
computed
- In SQL, a subquery can appear in the FROM or WHERE
or HAVING clause
Winter 2003 13
M eaning of N ested Q u ery in W H ER E
c lau se
- Result1: Compute the cartesian product of all relations in
the relation list in outer query
- Result2: For every tuple in Result1, apply the condition
stated in the qualification list. ((Re)compute the subquery
in order to apply the condition in the qualification list)
Eliminate the tuple if the condition is not satisfied.
- Result3: Retrieve only the required components from
each tuple in Result2 according to target list
- Result: Eliminate duplicate rows in Result3 if DISTINCT
keyword is present in the SELECT clause
Winter 2003 14
C orrel ated N ested Q ueri es
- In all the examples so far, the inner query is independent
of the outer query
- The inner query could also depend on the outer query
- Example: Find the names of customers who have been
on the slope on 01/07/
Correlation via range variable c SELECT cname FROM Customers c WHERE EXISTS (SELECT * FROM Activities a
WHERE a.sid = c.sid a.day=“01/07/03”)
Checks that the subquery returns a non-empty result
Winter 2003 15
A n oth er ex am p le
- Find all customers who went on the slope “Olympic Lady”
SELECT sid FROM Customers c WHERE EXISTS (SELECT a.sid FROM Activities a WHERE a.sid = c.sid AND a.slope-id IN (SELECT slope-id FROM Slopes s WHERE s.name=‘Olympic Lady’))
Winter 2003 16
S et com p ari son op erators
- IN, EXISTS, UNIQUE, op ANY (or op SOME), op ALL where op is one of {<,
- x IN Q
- Returns true if x occurs in the set Q
- x NOT IN Q
- Returns true if x does not occur in Q
- EXISTS Q
- Returns true if Q is a non-empty set
- NOT EXISTS Q
- Returns true if Q is empty
- What does the following mean?
Winter 2003 19
M ore ex am p les
- Find the names of all skiers whose age is greater than every snowboarder SELECT c.name FROM Customers c
WHERE c.type=“skier” c.age >ALL (SELECT c.age
FROM Customers c WHERE c.type = ‘snowboard’)
- Find the name of the oldest customers
SELECT cname FROM Customer c WHERE c.age >= ALL (SELECT c.age FROM Customers c)
Winter 2003 20
A g g reg ates
- Compute summary results over a table. E.g.,
- find the average/min/max score of all students who took CS
- find the total number of snowboarders
- find total salary of employees in Sales department
- SQL:
- COUNT, SUM, AVG, MIN, MAX
Winter 2003 21
C O U N T
- Find the total number of customers SELECT COUNT(sid) FROM Customers
- Find the total number of days of operation SELECT COUNT(distinct(day)) FROM Activities
Answer: 3
SELECT COUNT(day) FROM Activities
Answer: 6
•Alternatively, the last query could have been written as SELECT COUNT(*) FROM Activities
Winter 2003 22
S U M , A V G
- SUM() and SUM(DISTINCT()) have similar obvious
meanings
- Find the total profit of the company
SELECT SUM(qty*price) FROM Sales
- Similarly for AVG() and AVG(DISTINCT())
Winter 2003 25
O n a si m ilar n ote…
- Find the activities of Luke
SELECT * FROM Activities a WHERE a.sid = (SELECT sid FROM Customers c WHERE cname=‘Luke’)
•If there is only one Luke in the Customers table, the subquery returns only one sid value. SQL returns that single sid value to be compared with a.sid •However, if the subquery returns more than one value, a run-time error occurs
Winter 2003 26
M ore E x am p les
- Find the names of all skiers whose age is greater than every snowboarder SELECT c.name FROM Customers c WHERE c.age >ALL (SELECT c.age FROM Customers c WHERE c.type = ‘snowboard’)
SELECT c.name FROM Customers c WHERE c.age > (SELECT MAX(c.age) FROM Customers c WHERE c.type = ‘snowboard’)
Previously…
Winter 2003 27
M ore E x am p les
- Find the names of all skiers whose age is greater than some snowboarder SELECT c.name FROM Customers c WHERE c.age >SOME (SELECT c.age FROM Customers c WHERE c.type = ‘snowboard’)
SELECT c.name FROM Customers c WHERE c.age > (SELECT MIN(c.age) FROM Customers c WHERE c.type = ‘snowboard’)
Winter 2003 28
O R D E R B Y
SELECT …
FROM …
WHERE …
ORDER BY c 1 , …, cn
- Sorts the result according to columns c 1 , …, cn
- By default, it sorts the result in ascending order
- Specify descending through ORDER BY c 1 , …, cn DESC
Winter 2003 31
G R O U P B Y an d H A V I N G
- More specifically, the target list consists of
- a list of column names
- and a list of terms having the form agg(column-name) AS new-name
- Every column in the list of column names must appear in grouping-list
- The expressions appearing in group-qualification must have a single value per group. HAVING states the condition that the resulting tuple (for a group) must satisfy before it can be emitted.
- If GROUP BY is omitted, the entire table is regarded as a group
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY grouping-list
HAVING group-qualification
Winter 2003 32
S em an ti cs
- Compute the cartesian product of all relations in the relation list in outer query
- For every tuple in Result1, apply the condition stated in the qualification list. ((Re)compute the subquery in order to apply the condition in the qualification list) Eliminate the tuple if the condition is not satisfied.
- Keep only the required columns: columns in the SELECT clause, GROUP BY, and HAVING clauses are kept
- Sort the table according to the GROUP BY columns
- Apply group-qualification to each group (according to the GROUP BY columns). Eliminate groups which do not satisfy the group- qualification
- Generate one tuple for each group according to SELECT clause
as before
Winter 2003 33
E x am p le
- 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 S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
92 Frodo 1 28. 38 Sam 1 30.
58 Rusty 10 35.
29 Brutus 1 33.
64 Horatio 7 35.
71 Zorba 10 16.
31 Lubber 8 55.
22 Dustin 7 45.
sid sname rating age
Winter 2003 34
E x am p le
- Take the cross product of all relations in the FROM clause
92 Frodo 1 28. 38 Sam 1 30.
58 Rusty 10 35.
29 Brutus 1 33.
64 Horatio 7 35.
71 Zorba 10 16.
31 Lubber 8 55.
22 Dustin 7 45.
sid sname rating age
SELECT S.rating, MIN (S.age)
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
Winter 2003 37
E x am p le
- Sort the table according to the GROUP BY columns (^1) 28. 1 30.
rating age
SELECT S.rating, MIN (S.age)
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
rating age
Winter 2003 38
E x am p le
- Apply group-qualification to each group according to the GROUP BY columns. Eliminate groups which do not satisfy the group-qualification
SELECT S.rating, MIN (S.age)
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
rating age
Winter 2003 39
E x am p le
- Generate one tuple for each group according to SELECT clause
SELECT S.rating, MIN (S.age)
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
rating age
Winter 2003 40
E V E R Y an d A N Y in H A V I N G
rating age
SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 AND EVERY (S.age
rating age