3) student (ufid, major) quiz(q_num, point_pos) q_score(q_num,ufid,points_scored) (in trc) a) which...

100

Post on 21-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:
Page 2: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

3) Student (ufid, major)Quiz(Q_num, point_pos)

Q_score(q_num,ufid,points_scored) (in TRC)

A) Which quizzes did a “CE” major score 100% on?

{ a[Q_num]: a Quiz ,s STUDENT ; t Q_score, s[ufid]=t[ufid] s[ufid]=“CE”

a[Q_num]=t[q_num]

t[points_scored]=100% }

Relational Algebra:

q_num [ Quiz |x| (major=“CE” Student) |x| ( points_scored=“100” Q_score))

Page 3: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Consider the following relational database schema:

Pizza(pid, pname, size)

Store(sname, phone, quality)

Soldby(pid, sname, price)

Express each of the following queries in the relational algebra.

a) Find the name of all stores that sell both veggie and cheese pizza.

Answer:

sname(pname = ‘veggie’ Pizza |X| Soldby)

sname(pname = ‘cheese’ Pizza |X| Soldby)

Page 4: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Consider the following relational database schema:Pizza(pid, pname, size)Store(sname, phone, quality)Soldby(pid, sname, price)

Express each of the following queries in the relational algebra.b) Find the names and phone numbers of all stores that sell

good or excellent veggie pizza under $10.

Answer:sname, phone((pname = ‘veggie’ Pizza) |X| (quality = ‘good’ Store) |X| (price <

10 Soldby)) sname, phone((pname = ‘veggie’ Pizza) |X| (quality = ‘excellent’ Store) |X| (price

< 10 Soldby))

Page 5: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Student (ufid, major)Quiz(Q_num, point_pos)

Q_score(q_num,ufid,points_scoredb) Who are the “CE” major who missed Quiz 3?

{ s [ufid]:s STUDENT. t Q_SCORE

s[ufid]=“CE”

t[q_num ]=“3” t[points_scored] =“null”

s[ufid]=t[ufid] }

Page 6: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Student (ufid, major)Quiz(Q_num, point_pos)

Q_score(q_num,ufid,points_scored c) Which students have a 0 score for 2 different

quizzes?{ s[ufid]: s STUDENT t1, t2 Q_SCORE

s[ufid]=t1[ufid]= t2[ufid]

t1[q_num] t2 [q_num]

t1 [point_score]=t2 [point_score]=“0” }

Page 7: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

7) Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)

book(isbn, title, publisher,dte) with key=(isbn)

a) Find the names of authors who wrote or co wrote books published in 1995

{a [name]: a Author w WROTE b Book

a.aid=w.aid w.isbn=b.isbn b.date=1995}

Page 8: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)

book(isbn, title, publisher,dte) with key=(isbn) b) Find the names of authors who were

always the first author of books they wrote

{ a[name]: a Author, w Wrote, b Book

a.aid=w.aid w.isbn = b.isbn w.order=1 }

Page 9: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn) c) Find the AID of author (if any) who have written or co written books published by every publisher of book?

Let Publisher = {b[publisher]: b Book }

{ a[aid]: a Author p Publisher w Wrote & b* Book

& a [aid]=w[aid] & w[isbn]= b*[isbn] & b*[publisher]=p }

Page 10: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

6 c) Author (aid, name, phone) with key =(aid)wrote(aid, isbn, order) with key =(aid, Isbn)book(isbn, title, publisher,dte) with key=(isbn

Find the aid of authors (if any) who have written or co-written books published by every publisher of books? (Relational Algebra, TRC)

Relational Algebra:

Let T = publisherBook,

aid [ (Author |x| Wrote|x| Book) T ]

Page 11: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Data Definition in SQLSo far we have see the Data Manipulation Language, DMLNext: Data Definition Language (DDL)

Data types: Defines the types.

Data definition: defining the schema.

• Create tables• Delete tables• Modify table schema

Indexes: to improve performance

Page 12: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Data Types in SQL

• Characters: – CHAR(20) -- fixed length– VARCHAR(40) -- variable length

• Numbers:– INT, REAL plus variations

• Times and dates: – DATE, TIME (Pointbase)

Page 13: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Creating Tables

CREATE TABLE Person(

name VARCHAR(30), social-security-number INT, age SHORTINT, city VARCHAR(30), gender BIT(1), Birthdate DATE

);

CREATE TABLE Person(

name VARCHAR(30), social-security-number INT, age SHORTINT, city VARCHAR(30), gender BIT(1), Birthdate DATE

);

Example:

Page 14: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

SQL Queries

• Principal form:SELECT desired attributesFROM tuple variables –– range over relationsWHERE condition about tuple variables;

Running example relation schema:Beers(name, manf)Bars(name, addr, license)Drinkers(name, addr, phone)Likes(drinker, beer)Sells(bar, beer, price)Frequents(drinker, bar)

Page 15: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

ExampleWhat beers are made by Anheuser-Busch?

Beers(name, manf)

SELECT nameFROM BeersWHERE manf = 'Anheuser-Busch';

• Note: single quotes for strings.nameBudBud LiteMichelob

Page 16: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 17: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Formal Semanticsof Single-Relation SQL Query

1. Start with the relation in the FROM clause.2. Apply (bag) , using condition in WHERE clause.3. Apply (extended, bag) using attributes in SELECT

clause.

Equivalent Operational SemanticsImagine a tuple variable ranging over all tuples of the

relation. For each tuple:• Check if it satisfies the WHERE clause.• Print the values of terms in SELECT, if so.

Page 18: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Star as List of All Attributes

Beers(name, manf)

SELECT *FROM BeersWHERE manf = 'Anheuser-Busch';

name manfBud Anheuser-BuschBud Lite Anheuser-BuschMichelob Anheuser-Busch

Page 19: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Renaming columns

Beers(name, manf)

SELECT name AS beerFROM BeersWHERE manf = 'Anheuser-Busch';

beerBudBud LiteMichelob

Page 20: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Expressions as Values in Columns

Sells(bar, beer, price)

SELECT bar, beer, price*120 AS priceInYenFROM Sells;

bar beer priceInYenJoe’s Bud 300Sue’s Miller 360… … …

• Note: no WHERE clause is OK.

Page 21: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

• Trick: If you want an answer with a particular string in each row, use that constant as an expression.Likes(drinker, beer)

SELECT drinker,'likes Bud' AS whoLikesBud

FROM LikesWHERE beer = 'Bud';

drinker whoLikesBudSally likes BudFred likes Bud… …

Page 22: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example• Find the price Joe's Bar charges for Bud.

Sells(bar, beer, price)

SELECT priceFROM SellsWHERE bar = 'Joe''s Bar' AND

beer = 'Bud';

• Note: two single-quotes in a character string represent one single quote.

• Conditions in WHERE clause can use logical operators AND, OR, NOT and parentheses in the usual way.

• Remember: SQL is case insensitive. Keywords like SELECT or AND can be written upper/lower case as you like.– Only inside quoted strings does case matter.

Page 23: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

UpdatesUPDATE relation SET list of assignments WHERE condition.

ExampleDrinker Fred's phone number is 555-1212.Drinkers(name, addr, phone)

UPDATE DrinkersSET phone = '555-1212'WHERE name = 'Fred';

ExampleMake $4 the maximum price for beer.• Updates many tuples at once.Sells(bar, beer, price)

UPDATE SellsSET price = 4.00WHERE price > 4.00;

Page 24: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Modifying the Database

Three kinds of modifications

• Insertions

• Deletions

• Updates

Sometimes they are all called “updates”

Page 25: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Deleting or Modifying a TableDeleting:

ALTER TABLE Person ADD phone CHAR(16);

ALTER TABLE Person DROP age;

ALTER TABLE Person ADD phone CHAR(16);

ALTER TABLE Person DROP age;

Altering: (adding or removing an attribute).

What happens when you make changes to the schema?

Example:

DROP Person; DROP Person; Example: Exercise with care !!

Page 26: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Default Values

Specifying default values:

CREATE TABLE Person( name VARCHAR(30), social-security-number INT, age SHORTINT DEFAULT 100, city VARCHAR(30) DEFAULT ‘Seattle’, gender CHAR(1) DEFAULT ‘?’, Birthdate DATE

CREATE TABLE Person( name VARCHAR(30), social-security-number INT, age SHORTINT DEFAULT 100, city VARCHAR(30) DEFAULT ‘Seattle’, gender CHAR(1) DEFAULT ‘?’, Birthdate DATE

The default of defaults: NULL

Page 27: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 28: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 29: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 30: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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)

Purchasecorrupted

Page 31: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 32: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 33: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 34: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Deletion

DELETE FROM relation WHERE condition.• Deletes all tuples satisfying the condition from the named

relation.

ExampleSally no longer likes Bud.Likes(drinker, beer)

DELETE FROM LikesWHERE drinker = 'Sally' AND

beer = 'Bud';

ExampleMake the Likes relation empty.DELETE FROM Likes;

Page 35: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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:

Page 36: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Patterns• % stands for any string.• _ stands for any one character.• “Attribute LIKE pattern” is a condition that is true if

the string value of the attribute matches the pattern.– Also NOT LIKE for negation.

ExampleFind drinkers whose phone has exchange 555.

Drinkers(name, addr, phone)

SELECT nameFROM DrinkersWHERE phone LIKE '%555-_ _ _ _’;

• Note patterns must be quoted, like strings.

Page 37: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Nulls

In place of a value in a tuple's component.• Interpretation is not exactly “missing value.”• There could be many reasons why no value is

present, e.g., “value inappropriate.”

Comparing Nulls to Values• 3rd truth value UNKNOWN.• A query only produces tuples if the WHERE-

condition evaluates to TRUE(UNKNOWN is not sufficient).

Page 38: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example

bar beer price

Joe's bar Bud NULLSELECT barFROM SellsWHERE price < 2.00 OR price >= 2.00;

UNKNOWN UNKNOWN

UNKNOWN

• Joe's Bar is not produced, even though the WHERE condition is a tautology.

Page 39: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

3-Valued LogicThink of true = 1; false = 0, and unknown = 1/2. Then:• AND = min.• OR = max.• NOT(x) = 1 – x.

Some Key Laws Fail to HoldExample: Law of the excluded middle, i.e.,

p OR NOT p = TRUE

• For 3-valued logic: if p = unknown, then left side = max(1/2,(1–1/2)) = 1/2 ≠ 1.

• Like bag algebra, there is no way known to make 3-valued logic conform to all the laws we expect for sets/2-valued logic, respectively.

Page 40: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Testing for NULL• The condition value = NULL always evaluates to UNKNOWN, even if the value is NULL!

• Use value IS NULL or value IS NOT NULL instead.

Page 41: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Multi-relation Queries

• List of relations in FROM clause.• Relation-dot-attribute disambiguates attributes from several

relations.

ExampleFind the beers that the frequenters of Joe's Bar like.

Likes(drinker, beer)Frequents(drinker, bar)

SELECT beerFROM Frequents, LikesWHERE bar = 'Joe''s Bar' AND

Frequents.drinker = Likes.drinker;

Page 42: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Formal Semantics of Multi-relation Queries

Same as for single relation, but start with the product of all

the relations mentioned in the FROM clause.

Operational SemanticsConsider a tuple variable for each relation in the FROM.

• Imagine these tuple variables each pointing to a tuple of

their relation, in all combinations (e.g., nested loops).

• If the current assignment of tuple-variables to tuples

makes the WHERE true, then output the attributes of the

SELECT.

Page 43: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

bar

Frequents

drinker beerdrinker

Likes

flSally

SallyJoe’s

Page 44: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Explicit Tuple VariablesSometimes we need to refer to two or more copies of a relation.• Use tuple variables as aliases of the relations.

ExampleFind pairs of beers by the same manufacturer.

Beers(name, manf)

SELECT b1.name, b2.nameFROM Beers b1, Beers b2WHERE b1.manf = b2.manf AND

b1.name < b2.name;

• SQL permits AS between relation and its tuple variable;Oracle does not.

• Note that b1.name < b2.name is needed to avoid producing (Bud, Bud) and to avoid producing a pair in both orders.

Page 45: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Subqueries

Result of a select-from-where query can be used in the where-clause of another query.

Simplest Case: Subquery Returns a Single, Unary Tuple

Find bars that serve Miller at the same price Joe charges for Bud.Sells(bar, beer, price)

SELECT barFROM SellsWHERE beer = 'Miller' AND price =

(SELECT priceFROM SellsWHERE bar = 'Joe''s Bar' AND

beer = 'Bud');• Notice the scoping rule: an attribute refers to the most closely nested

relation with that attribute.• Parentheses around subquery are essential.

Page 46: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

The IN Operator“Tuple IN relation” is true iff the tuple is in the relation.

ExampleFind the name and manufacturer of beers that Fred likes.

Beers(name, manf)Likes(drinker, beer)

SELECT *FROM BeersWHERE name IN

(SELECT beerFROM LikesWHERE drinker = 'Fred’);

• Also: NOT IN.

Page 47: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

EXISTS“EXISTS(relation)” is true iff the relation is nonempty.

ExampleFind the beers that are the unique beer by their manufacturer.

Beers(name, manf)

SELECT nameFROM Beers b1WHERE NOT EXISTS

(SELECT * FROM Beers WHERE manf = b1.manf AND

name <> b1.name);

• Note scoping rule: to refer to outer Beers in the inner subquery, we need to give the outer a tuple variable, b1 in this example.

• A subquery that refers to values from a surrounding query is called a correlated subquery.

Page 48: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

QuantifiersANY and ALL behave as existential and universal quantifiers,

respectively.• Beware: in common parlance, “any” and “all” seem to be

synonyms, e.g., “I am fatter than any of you” vs. “I am fatter than all of you.” But in SQL:

ExampleFind the beer(s) sold for the highest price.

Sells(bar, beer, price)

SELECT beerFROM SellsWHERE price >= ALL(

SELECT priceFROM Sells);

Class ProblemFind the beer(s) not sold for the lowest price.

Page 49: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Union, Intersection, Difference“(subquery) UNION (subquery)” produces the union of the two relations.• Similarly for INTERSECT, EXCEPT = intersection and set difference.

– But: in Oracle set difference is MINUS, not EXCEPT.

ExampleFind the drinkers and beers such that the drinker likes the beer and

frequents a bar that serves it.Likes(drinker, beer)Sells(bar, beer, price)Frequents(drinker, bar)

(SELECT * FROM Likes)INTERSECT

(SELECT drinker, beer FROM Sells, Frequents WHERE Frequents.bar = Sells.bar);

Page 50: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example

Find the different prices charged for beers.Sells(bar, beer, price)

SELECT DISTINCT priceFROM Sells;

Page 51: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Join-Based ExpressionsA number of forms are provided.• Can be used either stand-alone (in place of a select-from-

where) or to define a relation in the FROM-clause.R NATURAL JOIN SR JOIN S ON condition

e.g., condition: R.B=S.BR CROSS JOIN SR OUTER JOIN S• Outerjoin can be modified by:1. Optional NATURAL in front.2. Optional ON condition at end.3. Optional LEFT, RIGHT, or FULL (default) before OUTER.

– LEFT = pad (with NULL) dangling tuples of R only; RIGHT = pad dangling tuples of S only.

Page 52: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Aggregations

Sum, avg, min, max, and count apply to attributes/columns. Also, count(*) applies to tuples.

• Use these in lists following SELECT.ExampleFind the average price of Bud.Sells(bar, beer, price)

SELECT AVG(price)FROM SellsWHERE beer = 'Bud';• Counts each tuple (presumably each bar that sells Bud)

once.Class ProblemWhat would we do if Sells were a bag?

Page 53: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Eliminating DuplicatesBefore Aggregation

Find the number of different prices at which Bud is sold.

Sells(bar, beer, price)

SELECT COUNT(DISTINCT price)

FROM Sells

WHERE beer = 'Bud';• DISTINCT may be used in any aggregation,

but typically only makes sense with COUNT.

Page 54: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

GroupingFollow select-from-where by GROUP BY and a list of

attributes.• The relation that is the result of the FROM and WHERE

clauses is grouped according to the values of these attributes, and aggregations take place only within a group.

ExampleFind the average sales price for each beer.Sells(bar, beer, price)

SELECT beer, AVG(price)FROM SellsGROUP BY beer;

Page 55: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example

Find, for each drinker, the average price of Bud at the bars they frequent.

Sells(bar, beer, price)Frequents(drinker, bar)

SELECT drinker, AVG(price)FROM Frequents, SellsWHERE beer = 'Bud' AND

Frequents.bar = Sells.barGROUP BY drinker;• Note: grouping occurs after the and

operations.

Page 56: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Restriction on SELECT Lists With Aggregation

If any aggregation is used, then each element of a SELECT clause must either be aggregated or appear in a group-by clause.

Example• The following might seem a tempting way to find the bar that

sells Bud the cheapest:Sells(bar, beer, price)

SELECT bar, MIN(price)FROM SellsWHERE beer = 'Bud';• But it is illegal in SQL.

ProblemHow would we find that bar?

Page 57: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

HAVING ClausesHAVING clauses are selections on groups, just as WHERE clauses are selections on tuples.

• Condition can use the tuple variables or relations in the FROM and their attributes, just like the WHERE can.– But the tuple variables range only over the group.– And the attribute better make sense within a group;

i.e., be one of the grouping attributes.

Page 58: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example

Find the average price of those beers that are either served in at least 3 bars or manufactured by Anheuser-Busch.

Beers(name, manf)Sells(bar, beer, price)

SELECT beer, AVG(price)FROM SellsGROUP BY beerHAVING COUNT(*) >= 3 OR

beer IN (SELECT nameFROM BeersWHERE manf = 'Anheuser-Busch');

Page 59: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

DB Modifications• Modification = insert + delete + update.

Insertion of a TupleINSERT INTO relation VALUES (list of values).• Inserts the tuple = list of values, associating values with

attributes in the order the attributes were declared.– Forget the order? List the attributes as arguments of the relation.

ExampleLikes(drinker, beer)Insert the fact that Sally likes Bud.INSERT INTO Likes(drinker, beer)VALUES('Sally', 'Bud');

Page 60: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Insertion of the Result of a QueryINSERT INTO relation (subquery).

ExampleCreate a (unary) table of all Sally's potential buddies, i.e., the people who

frequent bars that Sally also frequents.Frequents(drinker, bar)

CREATE TABLE PotBuddies(name char(30)

);

INSERT INTO PotBuddies(SELECT DISTINCT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = 'Sally' AND

d2.drinker <> 'Sally' AND d1.bar = d2.bar

);

Page 61: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Example• Delete all beers for which there is another beer by

the same manufacturer.Beers(name, manf)

DELETE FROM Beers bWHERE EXISTS

(SELECT name FROM Beers WHERE manf = b.manf AND

name <> b.name);

• Note alias for relation from which deletion occurs.

Page 62: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

• Semantics is tricky. If A.B. makes Bud and BudLite (only), does deletion of Bud make BudLite not satisfy the condition?

• SQL semantics: all conditions in modifications must be evaluated by the system before any mods due to that mod command occur.– In Bud/Budlite example, we would first identify

both beers a targets, and then delete both.

Page 63: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 64: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Subqueries

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 65: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 66: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 67: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 68: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 69: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 70: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 71: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 Product.price < 100

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

Existential: easy !

Page 72: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 73: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 Product.price >= 100

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

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

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

Page 74: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 it can be null (nullable attribute) or not

• How does SQL cope with tables that have NULLs ?

Page 75: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 76: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 77: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 78: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 79: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 80: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 81: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 82: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 83: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 84: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Aggregation: Count

SELECT Count(*)FROM ProductWHERE year > 1995

SELECT Count(*)FROM ProductWHERE year > 1995

Except COUNT, all aggregations apply to a single attribute

Page 85: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 86: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 87: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 88: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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”GROUP BY product

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

Let’s see what this means…

Page 89: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Grouping and Aggregation

1. Compute the FROM and WHERE clauses.2. Group by the attributes in the GROUP BY3. Produce one tuple for every group by applying aggregation

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

Page 90: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 91: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Then, aggregate

Product TotalSales

Bagel $29.75

Banana $12.48

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

Page 92: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 93: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 94: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 30 items sold.

HAVING clause contains conditions on aggregates.

Page 95: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 96: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

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 97: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Aggregation

Author(login,name)

Document(url, title)

Wrote(login,url)

Mentions(url,word)

Page 98: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Grouping vs. Nested Queries

• 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 99: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Grouping vs. Nested Queries

• 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 100: 3) Student (ufid, major) Quiz(Q_num, point_pos) Q_score(q_num,ufid,points_scored) (in TRC) A) Which quizzes did a “CE” major score 100% on? { a[Q_num]:

Grouping vs. Nested Queries

• 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