lecture 04: sql

38
1 Lecture 04: SQL Monday, October 6, 2003

Upload: nola

Post on 06-Jan-2016

30 views

Category:

Documents


0 download

DESCRIPTION

Lecture 04: SQL. Monday, October 6, 2003. Outline. Getting around INTERSECT and EXCEPT Aggregations (6.4.3 – 6.4.6) Nulls (6.1.6) Outer joins (6.3.8) Database Modifications (6.5). INTERSECT and EXCEPT: Not in SQL Server. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture 04: SQL

1

Lecture 04: SQL

Monday, October 6, 2003

Page 2: Lecture 04: SQL

2

Outline

• Getting around INTERSECT and EXCEPT

• Aggregations (6.4.3 – 6.4.6)

• Nulls (6.1.6)

• Outer joins (6.3.8)

• Database Modifications (6.5)

Page 3: Lecture 04: SQL

3

INTERSECT and EXCEPT:Not in SQL Server

(SELECT R.A, R.BFROM R) INTERSECT(SELECT S.A, S.BFROM S)

(SELECT R.A, R.BFROM R) INTERSECT(SELECT S.A, S.BFROM S)

SELECT R.A, R.BFROM RWHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)

SELECT R.A, R.BFROM RWHERE EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)

(SELECT R.A, R.BFROM R) EXCEPT(SELECT S.A, S.BFROM S)

(SELECT R.A, R.BFROM R) EXCEPT(SELECT S.A, S.BFROM S)

SELECT R.A, R.BFROM RWHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)

SELECT R.A, R.BFROM RWHERE NOT EXISTS(SELECT * FROM S WHERE R.A=S.A and R.B=S.B)

If R, S have noduplicates, then can

write withoutsubqueries(HOW ?)

Page 4: Lecture 04: SQL

4

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 5: Lecture 04: SQL

5

Aggregation: Count

SELECT Count(*)FROM ProductWHERE year > 1995

SELECT Count(*)FROM ProductWHERE year > 1995

Except COUNT, all aggregations apply to a single attribute

Page 6: Lecture 04: SQL

6

Aggregation: Count

COUNT applies to duplicates, unless otherwise stated:

Better:

SELECT Count(category)FROM ProductWHERE year > 1995

SELECT Count(category)FROM ProductWHERE year > 1995

SELECT Count(DISTINCT category)FROM ProductWHERE year > 1995

SELECT Count(DISTINCT category)FROM ProductWHERE year > 1995

same as Count(*)

Page 7: Lecture 04: SQL

7

Simple Aggregation

Purchase(product, date, price, quantity)

Example 1: find total sales for the entire database

Example 1’: find total sales of bagels

SELECT Sum(price * quantity)FROM Purchase

SELECT Sum(price * quantity)FROM Purchase

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

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

Page 8: Lecture 04: SQL

8

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 9: Lecture 04: SQL

9

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 10: Lecture 04: SQL

10

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 11: Lecture 04: SQL

11

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 12: Lecture 04: SQL

12

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 13: Lecture 04: SQL

13

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 14: Lecture 04: SQL

14

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 15: Lecture 04: SQL

15

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 16: Lecture 04: SQL

16

General form of Grouping and Aggregation

SELECT S

FROM R1,…,Rn

WHERE C1

GROUP BY a1,…,ak

HAVING C2

S = may contain some of group-by 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 17: Lecture 04: SQL

17

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 18: Lecture 04: SQL

18

Examples of Queries with Aggregation

Web pages, and their authors:

Author(login,name)

Document(url, title)

Wrote(login,url)

Mentions(url,word)

Page 19: Lecture 04: SQL

19

• Find all authors who wrote at least 10 documents Author(login,name) Wrote(login,url)

• 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 writtenby a novice

Page 20: Lecture 04: SQL

20

• 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 21: Lecture 04: SQL

21

• 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

Page 22: Lecture 04: SQL

22

NULLS in SQL

• Whenever we don’t have a value, we can put a NULL

• Can mean many things:– Value does not exists

– Value exists but is unknown

– Value not applicable

– Etc.

• The schema specifies for each attribute if can be null (nullable attribute) or not

• How does SQL cope with tables that have NULLs ?

Page 23: Lecture 04: SQL

23

Null Values

• If x= NULL then 4*(3-x)/7 is still NULL

• If x= NULL then x=“Joe” is UNKNOWN

• In SQL there are three boolean values:FALSE = 0

UNKNOWN = 0.5

TRUE = 1

Page 24: Lecture 04: SQL

24

Null Values

• C1 AND C2 = min(C1, C2)• C1 OR C2 = max(C1, C2)• NOT C1 = 1 – C1

Rule in SQL: include only tuples that yield TRUE

SELECT *FROM PersonWHERE (age < 25) AND (height > 6 OR weight > 190)

SELECT *FROM PersonWHERE (age < 25) AND (height > 6 OR weight > 190)

E.g.age=20heigth=NULLweight=200

Page 25: Lecture 04: SQL

25

Null Values

Unexpected behavior:

Some Persons are not included !

SELECT *FROM PersonWHERE age < 25 OR age >= 25

SELECT *FROM PersonWHERE age < 25 OR age >= 25

Page 26: Lecture 04: SQL

26

Null Values

Can test for NULL explicitly:– x IS NULL– x IS NOT NULL

Now it includes all Persons

SELECT *FROM PersonWHERE age < 25 OR age >= 25 OR age IS NULL

SELECT *FROM PersonWHERE age < 25 OR age >= 25 OR age IS NULL

Page 27: Lecture 04: SQL

27

OuterjoinsExplicit joins in SQL:

Product(name, category) Purchase(prodName, store)

Same as:

But Products that never sold will be lost !

SELECT Product.name, Purchase.storeFROM Product JOIN Purchase ON Product.name = Purchase.prodName

SELECT Product.name, Purchase.storeFROM Product JOIN Purchase ON Product.name = Purchase.prodName

SELECT Product.name, Purchase.storeFROM Product, PurchaseWHERE Product.name = Purchase.prodName

SELECT Product.name, Purchase.storeFROM Product, PurchaseWHERE Product.name = Purchase.prodName

Page 28: Lecture 04: SQL

28

Outerjoins

Left outer joins in SQL:Product(name, category)

Purchase(prodName, store)

SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName

SELECT Product.name, Purchase.store FROM Product LEFT OUTER JOIN Purchase ON Product.name = Purchase.prodName

Page 29: Lecture 04: SQL

29

Name Category

Gizmo gadget

Camera Photo

OneClick Photo

ProdName Store

Gizmo Wiz

Camera Ritz

Camera Wiz

Name Store

Gizmo Wiz

Camera Ritz

Camera Wiz

OneClick NULL

Product Purchase

Page 30: Lecture 04: SQL

30

Outer Joins

• Left outer join:– Include the left tuple even if there’s no match

• Right outer join:– Include the right tuple even if there’s no match

• Full outer join:– Include the both left and right tuples even if

there’s no match

Page 31: Lecture 04: SQL

31

Modifying the Database

Three kinds of modifications

• Insertions

• Deletions

• Updates

Sometimes they are all called “updates”

Page 32: Lecture 04: SQL

32

InsertionsGeneral form:

Missing attribute NULL.May drop attribute names if give them in order.

INSERT INTO R(A1,…., An) VALUES (v1,…., vn) INSERT INTO R(A1,…., An) VALUES (v1,…., vn)

INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’)

INSERT INTO Purchase(buyer, seller, product, store) VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’)

Example: Insert a new purchase to the database:

Page 33: Lecture 04: SQL

33

Insertions

INSERT INTO PRODUCT(name)

SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01”

INSERT INTO PRODUCT(name)

SELECT DISTINCT Purchase.product FROM Purchase WHERE Purchase.date > “10/26/01”

The query replaces the VALUES keyword.Here we insert many tuples into PRODUCT

Page 34: Lecture 04: SQL

34

Insertion: an Example

prodName is foreign key in Product.name

Suppose database got corrupted and we need to fix it:

name listPrice category

gizmo 100 gadgets

prodName buyerName price

camera John 200

gizmo Smith 80

camera Smith 225

Task: insert in Product all prodNames from Purchase

Product

Product(name, listPrice, category)Purchase(prodName, buyerName, price)

Product(name, listPrice, category)Purchase(prodName, buyerName, price)

Purchase

Page 35: Lecture 04: SQL

35

Insertion: an Example

INSERT INTO Product(name)

SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product)

INSERT INTO Product(name)

SELECT DISTINCT prodName FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product)

name listPrice category

gizmo 100 Gadgets

camera - -

Page 36: Lecture 04: SQL

36

Insertion: an Example

INSERT INTO Product(name, listPrice)

SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product)

INSERT INTO Product(name, listPrice)

SELECT DISTINCT prodName, price FROM Purchase WHERE prodName NOT IN (SELECT name FROM Product)

name listPrice category

gizmo 100 Gadgets

camera 200 -

camera ?? 225 ?? - Depends on the implementation

Page 37: Lecture 04: SQL

37

Deletions

DELETE FROM PURCHASE

WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’

DELETE FROM PURCHASE

WHERE seller = ‘Joe’ AND product = ‘Brooklyn Bridge’

Factoid about SQL: there is no way to delete only a single

occurrence of a tuple that appears twice

in a relation.

Example:

Page 38: Lecture 04: SQL

38

Updates

UPDATE PRODUCTSET price = price/2WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);

UPDATE PRODUCTSET price = price/2WHERE Product.name IN (SELECT product FROM Purchase WHERE Date =‘Oct, 25, 1999’);

Example: