lecture 03: sql

42
1 Lecture 03: SQL Monday, October 4, 2004

Upload: kaiyo

Post on 09-Jan-2016

28 views

Category:

Documents


4 download

DESCRIPTION

Lecture 03: SQL. Monday, October 4, 2004. Project: Phase 1 (out of 3). Domain 1: Inventory - Abramsky to Hanni Domain 2: Billing - Henning to O'Connell Domain 3: Shipping - Paija Pun to Zhurid October 15: Relational Schema for phase I due. October 25: Project Phase I due. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture 03: SQL

1

Lecture 03: SQL

Monday, October 4, 2004

Page 2: Lecture 03: SQL

2

Project: Phase 1 (out of 3)

• Domain 1: Inventory - Abramsky to Hanni• Domain 2: Billing - Henning to O'Connell• Domain 3: Shipping - Paija Pun to Zhurid

• October 15: Relational Schema for phase I due.• October 25: Project Phase I due.

• See course website, but note that it is still subject to change in the next two days

Page 3: Lecture 03: SQL

3

Project: Phase 1

• Read your domain specification

• Create the Schema, populate the database, send us the schema and the data by October 15

• Then create a Webpage: due October 25

• Start working on the Webpage before the 15th !!

• Questions ? Ask me or Victor Tung

Page 4: Lecture 03: SQL

4

Outline

• Unions, intersections, differences(6.2.5, 6.4.2)

• Subqueries (6.3)

• Aggregations (6.4.3 – 6.4.6)

Hint for reading the textbook: read the entire chapter 6 !

Reading assignment from “SQL for Nerds”: chapter 4, “Morecomplex queries” (you will find it very useful for subqueries)

Page 5: Lecture 03: SQL

5

Tuple Variables in SQL

SELECT DISTINCT x.storeFROM Purchase AS x, Purchase AS yWHERE x.product = y.product AND y.store = ‘BestBuy’

SELECT DISTINCT x.storeFROM Purchase AS x, Purchase AS yWHERE x.product = y.product AND y.store = ‘BestBuy’

Find all stores that sold at least one product that was soldat ‘BestBuy’:

Purchase (buyer, seller, store, product)

Page 6: Lecture 03: SQL

6

Tuple VariablesGeneral rule: tuple variables introduced automatically by the system: Product ( name, price, category, manufacturer)

Becomes:

Doesn’t work when Product occurs more than once:In that case the user needs to define variables explicitely.

SELECT name FROM Product WHERE price > 100

SELECT name FROM Product WHERE price > 100

SELECT Product.name FROM Product AS Product WHERE Product.price > 100

SELECT Product.name FROM Product AS Product WHERE Product.price > 100

Page 7: Lecture 03: SQL

7

Meaning (Semantics) of SQL Queries

SELECT a1, a2, …, akFROM R1 AS x1, R2 AS x2, …, Rn AS xnWHERE Conditions

1. Nested loops:

Answer = {}for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer {(a1,…,ak)}return Answer

Answer = {}for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer {(a1,…,ak)}return Answer

Page 8: Lecture 03: SQL

8

Meaning (Semantics) of SQL Queries

SELECT a1, a2, …, akFROM R1 AS x1, R2 AS x2, …, Rn AS xnWHERE Conditions

2. Parallel assignment

Doesn’t impose any order !

Answer = {}for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer {(a1,…,ak)}return Answer

Answer = {}for all assignments x1 in R1, …, xn in Rn do if Conditions then Answer = Answer {(a1,…,ak)}return Answer

Page 9: Lecture 03: SQL

9

First Unintuitive SQLismSELECT DISTINCT R.AFROM R, S, TWHERE R.A=S.A OR R.A=T.A

Looking for R (S T)∩ ∪

But what happens if T is empty?

Page 10: Lecture 03: SQL

10

Renaming Columns

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

SELECT Pname AS prodName, Price AS askPriceFROM ProductWHERE Price > 100

SELECT Pname AS prodName, Price AS askPriceFROM ProductWHERE Price > 100

Product

prodName askPrice

SingleTouch $149.99

MultiTouch $203.99Query withrenaming

Page 11: Lecture 03: SQL

11

Union, Intersection, Difference(SELECT name FROM Person WHERE City=“Seattle”)

UNION

(SELECT name FROM Person, Purchase WHERE buyer=name AND store=“The Bon”)

(SELECT name FROM Person WHERE City=“Seattle”)

UNION

(SELECT name FROM Person, Purchase WHERE buyer=name AND store=“The Bon”)

Similarly, you can use INTERSECT and EXCEPT.You must have the same attribute names (otherwise: rename).

Page 12: Lecture 03: SQL

12

Conserving Duplicates

(SELECT name FROM Person WHERE City=“Seattle”)

UNION ALL

(SELECT name FROM Person, Purchase WHERE buyer=name AND store=“The Bon”)

(SELECT name FROM Person WHERE City=“Seattle”)

UNION ALL

(SELECT name FROM Person, Purchase WHERE buyer=name AND store=“The Bon”)

Page 13: Lecture 03: SQL

13

Subqueries

A subquery producing a single value:

In this case, the subquery returns one value.

If it returns more, it’s a run-time error.

SELECT Purchase.productFROM PurchaseWHERE buyer = (SELECT name FROM Person WHERE ssn = ‘123456789‘);

SELECT Purchase.productFROM PurchaseWHERE buyer = (SELECT name FROM Person WHERE ssn = ‘123456789‘);

Page 14: Lecture 03: SQL

14

Can say the same thing without a subquery:

This is equivalent to the previous one when the ssn is a keyand ‘123456789’ exists in the database;otherwise they are different.

SELECT Purchase.productFROM Purchase, PersonWHERE buyer = name AND ssn = ‘123456789‘

SELECT Purchase.productFROM Purchase, PersonWHERE buyer = name AND ssn = ‘123456789‘

Page 15: Lecture 03: SQL

15

Subqueries Returning Relations

SELECT Company.name FROM Company, Product WHERE Company.name=Product.maker AND Product.name IN (SELECT Purchase.product FROM Purchase WHERE Purchase .buyer = ‘Joe Blow‘);

SELECT Company.name FROM Company, Product WHERE Company.name=Product.maker AND Product.name IN (SELECT Purchase.product FROM Purchase WHERE Purchase .buyer = ‘Joe Blow‘);

Find companies that manufacture products bought by Joe Blow.

Here the subquery returns a set of values: no moreruntime errors.

Page 16: Lecture 03: SQL

16

Subqueries Returning Relations

SELECT Company.name FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.name = Purchase.product AND Purchase.buyer = ‘Joe Blow’

SELECT Company.name FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.name = Purchase.product AND Purchase.buyer = ‘Joe Blow’

Equivalent to:

Is this query equivalent to the previous one ?

Beware of duplicates !

Page 17: Lecture 03: SQL

17

Removing Duplicates

SELECT DISTINCT Company.name FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.name = Purchase.product AND Purchase.buyer = ‘Joe Blow’

SELECT DISTINCT Company.name FROM Company, Product, Purchase WHERE Company.name= Product.maker AND Product.name = Purchase.product AND Purchase.buyer = ‘Joe Blow’

SELECT DISTINCT Company.name FROM Company, Product WHERE Company.name= Product.maker AND Product.name IN (SELECT Purchase.product FROM Purchase WHERE Purchase.buyer = ‘Joe Blow’)

SELECT DISTINCT Company.name FROM Company, Product WHERE Company.name= Product.maker AND Product.name IN (SELECT Purchase.product FROM Purchase WHERE Purchase.buyer = ‘Joe Blow’)

Nowthey are equivalent

Page 18: Lecture 03: SQL

18

Subqueries Returning Relations

SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘Gizmo-Works’)

SELECT name FROM Product WHERE price > ALL (SELECT price FROM Purchase WHERE maker=‘Gizmo-Works’)

Product ( pname, price, category, maker)Find products that are more expensive than all those producedBy “Gizmo-Works”

You can also use: s > ALL R s > ANY R EXISTS R

Page 19: Lecture 03: SQL

19

Question for Database Fansand their Friends

• Can we express this query as a single SELECT-FROM-WHERE query, without subqueries ?

• Hint: show that all SFW queries are monotone (figure out what this means). A query with ALL is not monotone

Page 20: Lecture 03: SQL

20

Correlated Queries

SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = x.title);

SELECT DISTINCT title FROM Movie AS x WHERE year <> ANY (SELECT year FROM Movie WHERE title = x.title);

Movie (title, year, director, length) Find movies whose title appears more than once.

Note (1) scope of variables (2) this can still be expressed as single SFW

correlation

Page 21: Lecture 03: SQL

21

Complex Correlated Query

Product ( pname, price, category, maker, year)• Find products (and their manufacturers) that are more expensive

than all products made by the same manufacturer before 1972

Powerful, but much harder to optimize !

SELECT DISTINCT pname, makerFROM Product AS xWHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);

SELECT DISTINCT pname, makerFROM Product AS xWHERE price > ALL (SELECT price FROM Product AS y WHERE x.maker = y.maker AND y.year < 1972);

Page 22: Lecture 03: SQL

22

Existential/Universal Conditions

Product ( pname, price, company)Company( cname, city)

Find all companies s.t. some of their products have price < 100

SELECT DISTINCT Company.cnameFROM Company, ProductWHERE Company.cname = Product.company and Produc.price < 100

SELECT DISTINCT Company.cnameFROM Company, ProductWHERE Company.cname = Product.company and Produc.price < 100

Existential: easy !

Page 23: Lecture 03: SQL

23

Existential/Universal Conditions

Product ( pname, price, company)Company( cname, city)

Find all companies s.t. all of their products have price < 100

Universal: hard !

Page 24: Lecture 03: SQL

24

Existential/Universal Conditions

2. Find all companies s.t. all their products have price < 100

1. Find the other companies: i.e. s.t. some product 100

SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100

SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname IN (SELECT Product.company FROM Product WHERE Produc.price >= 100

SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100

SELECT DISTINCT Company.cnameFROM CompanyWHERE Company.cname NOT IN (SELECT Product.company FROM Product WHERE Produc.price >= 100

Page 25: Lecture 03: SQL

25

Aggregation

SELECT Avg(price)FROM ProductWHERE maker=“Toyota”

SELECT Avg(price)FROM ProductWHERE maker=“Toyota”

SQL supports several aggregation operations:

SUM, MIN, MAX, AVG, COUNT

Page 26: Lecture 03: SQL

26

Aggregation: Count

SELECT Count(*)FROM ProductWHERE year > 1995

SELECT Count(*)FROM ProductWHERE year > 1995

Except COUNT, all aggregations apply to a single attribute

Page 27: Lecture 03: SQL

27

Aggregation: Count

COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)FROM ProductWHERE year > 1995

Better:

SELECT Count(DISTINCT category)FROM ProductWHERE year > 1995

Page 28: Lecture 03: SQL

28

Simple Aggregation

Purchase(product, date, price, quantity)

Example 1: find total sales for the entire database

SELECT Sum(price * quantity)FROM Purchase

Example 1’: find total sales of bagels

SELECT Sum(price * quantity)FROM PurchaseWHERE product = ‘bagel’

Page 29: Lecture 03: SQL

29

Simple Aggregations

Product Date Price Quantity

Bagel 10/21 0.85 15

Banana 10/22 0.52 7

Banana 10/19 0.52 17

Bagel 10/20 0.85 20

Purchase

Page 30: Lecture 03: SQL

30

Grouping and AggregationUsually, we want aggregations on certain parts of the relation.

Purchase(product, date, price, quantity)

Example 2: find total sales after 9/1 per product.

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUPBY product

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUPBY product

Let’s see what this means…

Page 31: Lecture 03: SQL

31

Grouping and Aggregation

1. Compute the FROM and WHERE clauses.2. Group by the attributes in the GROUPBY3. Select one tuple for every group (and apply aggregation)

SELECT can have (1) grouped attributes or (2) aggregates.

Page 32: Lecture 03: SQL

32

First compute the FROM-WHERE clauses (date > “9/1”) then GROUP BY product:

Product Date Price Quantity

Banana 10/19 0.52 17

Banana 10/22 0.52 7

Bagel 10/20 0.85 20

Bagel 10/21 0.85 15

Page 33: Lecture 03: SQL

33

Then, aggregate

Product TotalSales

Bagel $29.75

Banana $12.48

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUPBY product

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUPBY product

Page 34: Lecture 03: SQL

34

GROUP BY v.s. Nested Quereis

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUP BY product

SELECT product, Sum(price*quantity) AS TotalSalesFROM PurchaseWHERE date > “9/1”GROUP BY product

SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘9/1’) AS TotalSalesFROM Purchase xWHERE x.date > “9/1”

SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity) FROM Purchase y WHERE x.product = y.product AND y.date > ‘9/1’) AS TotalSalesFROM Purchase xWHERE x.date > “9/1”

Page 35: Lecture 03: SQL

35

Another Example

SELECT product, Sum(price * quantity) AS SumSales Max(quantity) AS MaxQuantityFROM PurchaseGROUP BY product

SELECT product, Sum(price * quantity) AS SumSales Max(quantity) AS MaxQuantityFROM PurchaseGROUP BY product

For every product, what is the total sales and max quantity sold?

Product SumSales MaxQuantity

Banana $12.48 17

Bagel $29.75 20

Page 36: Lecture 03: SQL

36

HAVING Clause

SELECT product, Sum(price * quantity)FROM PurchaseWHERE date > “9/1”GROUP BY productHAVING Sum(quantity) > 30

SELECT product, Sum(price * quantity)FROM PurchaseWHERE date > “9/1”GROUP BY productHAVING Sum(quantity) > 30

Same query, except that we consider only products that hadat least 100 buyers.

HAVING clause contains conditions on aggregates.

Page 37: Lecture 03: SQL

37

General form of Grouping and Aggregation

SELECT S

FROM R1,…,Rn

WHERE C1

GROUP BY a1,…,ak

HAVING C2

S = may contain attributes a1,…,ak and/or any aggregates but NO OTHER ATTRIBUTES

C1 = is any condition on the attributes in R1,…,Rn

C2 = is any condition on aggregate expressions

Why ?

Page 38: Lecture 03: SQL

38

General form of Grouping and Aggregation

SELECT S

FROM R1,…,Rn

WHERE C1

GROUP BY a1,…,ak

HAVING C2

Evaluation steps:1. Compute the FROM-WHERE part, obtain a table with all attributes

in R1,…,Rn

2. Group by the attributes a1,…,ak

3. Compute the aggregates in C2 and keep only groups satisfying C24. Compute aggregates in S and return the result

Page 39: Lecture 03: SQL

39

Aggregation

Author(login,name)

Document(url, title)

Wrote(login,url)

Mentions(url,word)

Page 40: Lecture 03: SQL

40

• Find all authors who wrote at least 10 documents:

• Attempt 1: with nested queries

SELECT DISTINCT Author.nameFROM AuthorWHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10

SELECT DISTINCT Author.nameFROM AuthorWHERE count(SELECT Wrote.url FROM Wrote WHERE Author.login=Wrote.login) > 10

This isSQL bya novice

Page 41: Lecture 03: SQL

41

• Find all authors who wrote at least 10 documents:

• Attempt 2: SQL style (with GROUP BY)

SELECT Author.nameFROM Author, WroteWHERE Author.login=Wrote.loginGROUP BY Author.nameHAVING count(wrote.url) > 10

SELECT Author.nameFROM Author, WroteWHERE Author.login=Wrote.loginGROUP BY Author.nameHAVING count(wrote.url) > 10

This isSQL byan expert

No need for DISTINCT: automatically from GROUP BY

Page 42: Lecture 03: SQL

42

• Find all authors who have a vocabulary over 10000 words:

SELECT Author.nameFROM Author, Wrote, MentionsWHERE Author.login=Wrote.login AND Wrote.url=Mentions.urlGROUP BY Author.nameHAVING count(distinct Mentions.word) > 10000

SELECT Author.nameFROM Author, Wrote, MentionsWHERE Author.login=Wrote.login AND Wrote.url=Mentions.urlGROUP BY Author.nameHAVING count(distinct Mentions.word) > 10000

Look carefully at the last two queries: you maybe tempted to write them as a nested queries,but in SQL we write them best with GROUP BY