1 / 100

# Prof. Sin-Min Lee - PowerPoint PPT Presentation

Final Revision 2. CS 157A Lecture 26. Prof. Sin-Min Lee. 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”

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Prof. Sin-Min Lee' - jason

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

CS 157A Lecture 26

Prof. Sin-Min Lee

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))

• 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.

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

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

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

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.

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))

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] }

Student (ufid, major)Quiz(Q_num, point_pos)Q_score(q_num,ufid,points_scoredc) 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” }

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}

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 }

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 }

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 ]

• So far we have see the Data Manipulation Language, DML

• Next: 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

• Characters:

• CHAR(20) -- fixed length

• VARCHAR(40) -- variable length

• Numbers:

• INT, REAL plus variations

• Times and dates:

• DATE, TIME (Pointbase)

Example:

CREATE TABLE Person(

name VARCHAR(30),

social-security-number INT,

age SHORTINT,

city VARCHAR(30),

gender BIT(1),

Birthdate DATE

);

• Principal form:

SELECT desired attributes

FROM tuple variables –– range over relations

Running example relation schema:

Beers(name, manf)

Likes(drinker, beer)

Sells(bar, beer, price)

Frequents(drinker, bar)

What beers are made by Anheuser-Busch?

Beers(name, manf)

SELECT name

FROM Beers

WHERE manf = 'Anheuser-Busch';

• Note: single quotes for strings.

name

Bud

Bud Lite

Michelob

(SELECT name

FROM Person

WHERE City=“Seattle”)

UNION

(SELECT name

FROM Person, Purchase

Similarly, you can use INTERSECT and EXCEPT.

You must have the same attribute names (otherwise: rename).

Formal Semanticsof Single-Relation SQL Query

• Apply (bag) , using condition in WHERE clause.

• Apply (extended, bag)  using attributes in SELECT clause.

Equivalent Operational Semantics

Imagine 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.

Beers(name, manf)

SELECT *

FROM Beers

WHERE manf = 'Anheuser-Busch';

name manf

Bud Anheuser-Busch

Bud Lite Anheuser-Busch

Michelob Anheuser-Busch

Beers(name, manf)

SELECT name AS beer

FROM Beers

WHERE manf = 'Anheuser-Busch';

beer

Bud

Bud Lite

Michelob

Sells(bar, beer, price)

SELECT bar, beer,

price*120 AS priceInYen

FROM Sells;

bar beer priceInYen

Joe’s Bud 300

Sue’s Miller 360

… … …

• Note: no WHERE clause is OK.

Example each row, use that constant as an expression.

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

Sells(bar, beer, price)

SELECT price

FROM Sells

WHERE 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.

Updates each row, use that constant as an expression.

UPDATE relation SET list of assignments WHERE condition.

Example

Drinker Fred's phone number is 555-1212.

UPDATE Drinkers

SET phone = '555-1212'

WHERE name = 'Fred';

Example

Make \$4 the maximum price for beer.

• Updates many tuples at once.

Sells(bar, beer, price)

UPDATE Sells

SET price = 4.00

WHERE price > 4.00;

Modifying the Database each row, use that constant as an expression.

Three kinds of modifications

• Insertions

• Deletions

Sometimes they are all called “updates”

Deleting or Modifying a Table each row, use that constant as an expression.

Deleting:

Exercise with care !!

Example:

DROP Person;

Altering: (adding or removing an attribute).

ALTER TABLE Person

ALTER TABLE Person

DROP age;

Example:

What happens when you make changes to the schema?

Default Values each row, use that constant as an expression.

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

The default of defaults: NULL

Conserving Duplicates each row, use that constant as an expression.

(SELECT name

FROM Person

WHERE City=“Seattle”)

UNIONALL

(SELECT name

FROM Person, Purchase

Insertions each row, use that constant as an expression.

General form:

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

Example: Insert a new purchase to the database:

INSERT INTO Purchase(buyer, seller, product, store)

VALUES (‘Joe’, ‘Fred’, ‘wakeup-clock-espresso-machine’, ‘The Sharper Image’)

Missing attribute  NULL.

May drop attribute names if give them in order.

Insertions each row, use that constant as an expression.

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

Insertion: an Example each row, use that constant as an expression.

Product(name, listPrice, category)

prodName is foreign key in Product.name

Suppose database got corrupted and we need to fix it:

corrupted

Purchase

Product

Task: insert in Product all prodNames from Purchase

Insertion: an Example each row, use that constant as an expression.

INSERT INTO Product(name)

SELECT DISTINCT prodName

FROM Purchase

WHERE prodName NOT IN (SELECT name FROM Product)

Insertion: an Example each row, use that constant as an expression.

INSERT INTO Product(name, listPrice)

SELECT DISTINCT prodName, price

FROM Purchase

WHERE prodName NOT IN (SELECT name FROM Product)

Depends on the implementation

Deletions each row, use that constant as an expression.

Example:

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.

Deletion each row, use that constant as an expression.

DELETE FROM relation WHERE condition.

• Deletes all tuples satisfying the condition from the named relation.

Example

Sally no longer likes Bud.

Likes(drinker, beer)

DELETE FROM Likes

WHERE drinker = 'Sally' AND

beer = 'Bud';

Example

Make the Likes relation empty.

DELETE FROM Likes;

Updates each row, use that constant as an expression.

Example:

UPDATE PRODUCT

SET price = price/2

WHERE Product.name IN

(SELECT product

FROM Purchase

WHERE Date =‘Oct, 25, 1999’);

Patterns each row, use that constant as an expression.

• % 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.

Example

Find drinkers whose phone has exchange 555.

SELECT name

FROM Drinkers

WHERE phone LIKE '%555-_ _ _ _’;

• Note patterns must be quoted, like strings.

Nulls each row, use that constant as an expression.

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).

Example each row, use that constant as an expression.

bar beer price

Joe's bar Bud NULL

SELECT bar

FROM Sells

WHERE price < 2.00 OR price >= 2.00;

UNKNOWN UNKNOWN

UNKNOWN

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

3-Valued Logic each row, use that constant as an expression.

Think of true = 1; false = 0, and unknown = 1/2. Then:

• AND = min.

• OR = max.

• NOT(x) = 1 – x.

Some Key Laws Fail to Hold

Example: Law of the excluded middle, i.e.,

pOR 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.

Testing for each row, use that constant as an expression.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.

Multi-relation Queries each row, use that constant as an expression.

• List of relations in FROM clause.

• Relation-dot-attribute disambiguates attributes from several relations.

Example

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

Likes(drinker, beer)

Frequents(drinker, bar)

SELECT beer

FROM Frequents, Likes

WHERE bar = 'Joe''s Bar' AND

Frequents.drinker = Likes.drinker;

Formal Semantics of Multi-relation Queries each row, use that constant as an expression.

Same as for single relation, but start with the product of all the relations mentioned in the FROM clause.

Operational Semantics

Consider 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.

Explicit Tuple Variables each row, use that constant as an expression.

Sometimes we need to refer to two or more copies of a relation.

• Use tuple variables as aliases of the relations.

Example

Find pairs of beers by the same manufacturer.

Beers(name, manf)

SELECT b1.name, b2.name

FROM Beers b1, Beers b2

WHERE 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.

Subqueries each row, use that constant as an expression.

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 bar

FROM Sells

WHERE beer = 'Miller' AND price =

(SELECT price

FROM Sells

WHERE 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.

The each row, use that constant as an expression.IN Operator

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

Example

Find the name and manufacturer of beers that Fred likes.

Beers(name, manf)

Likes(drinker, beer)

SELECT *

FROM Beers

WHERE name IN

(SELECT beer

FROM Likes

WHERE drinker = 'Fred’);

• Also: NOT IN.

EXISTS each row, use that constant as an expression.

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

Example

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

Beers(name, manf)

SELECT name

FROM Beers b1

WHERE 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.

Quantifiers each row, use that constant as an expression.

ANY 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:

Example

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

Sells(bar, beer, price)

SELECT beer

FROM Sells

WHERE price >= ALL(

SELECT price

FROM Sells);

Class Problem

Find the beer(s) not sold for the lowest price.

Union, Intersection, Difference each row, use that constant as an expression.

“(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.

Example

Find 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

);

Example each row, use that constant as an expression.

Find the different prices charged for beers.

Sells(bar, beer, price)

SELECT DISTINCT price

FROM Sells;

Join-Based Expressions each row, use that constant as an expression.

A 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 S

R JOIN S ON condition

e.g., condition:R.B=S.B

R CROSS JOIN S

R 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.

Aggregations each row, use that constant as an expression.

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

• Use these in lists following SELECT.

Example

Find the average price of Bud.

Sells(bar, beer, price)

SELECT AVG(price)

FROM Sells

WHERE beer = 'Bud';

• Counts each tuple (presumably each bar that sells Bud) once.

Class Problem

What would we do if Sells were a bag?

Eliminating Duplicates each row, use that constant as an expression.Before 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.

Grouping each row, use that constant as an expression.

Follow 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.

Example

Find the average sales price for each beer.

Sells(bar, beer, price)

SELECT beer, AVG(price)

FROM Sells

GROUP BY beer;

Example each row, use that constant as an expression.

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, Sells

WHERE beer = 'Bud' AND

Frequents.bar = Sells.bar

GROUP BY drinker;

• Note: grouping occurs after the  and  operations.

Restriction on each row, use that constant as an expression.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 Sells

WHERE beer = 'Bud';

• But it is illegal in SQL.

Problem

How would we find that bar?

HAVING each row, use that constant as an expression. Clauses

HAVING 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.

Example each row, use that constant as an expression.

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 Sells

GROUP BY beer

HAVING COUNT(*) >= 3 OR

beer IN (

SELECT name

FROM Beers

WHERE manf = 'Anheuser-Busch'

);

DB Modifications each row, use that constant as an expression.

• Modification = insert + delete + update.

Insertion of a Tuple

INSERT 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.

Example

Likes(drinker, beer)

Insert the fact that Sally likes Bud.

INSERT INTO Likes(drinker, beer)

VALUES('Sally', 'Bud');

Insertion of the Result of a Query each row, use that constant as an expression.

INSERT INTO relation (subquery).

Example

Create 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

);

Example each row, use that constant as an expression.

• Delete all beers for which there is another beer by the same manufacturer.

Beers(name, manf)

DELETE FROM Beers b

WHERE EXISTS

(SELECT name

FROM Beers

WHERE manf = b.manf AND

name <> b.name

);

• Note alias for relation from which deletion occurs.

• 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.

Subqueries does deletion of Bud make BudLite

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.product

FROM Purchase

(SELECT name

FROM Person

WHERE ssn = ‘123456789‘);

Subqueries does deletion of Bud make BudLite

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‘

Subqueries Returning Relations does deletion of Bud make BudLite

Find companies that manufacture products bought by 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‘);

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

Subqueries Returning Relations does deletion of Bud make BudLite

Equivalent to:

SELECT Company.name

FROM Company, Product, Purchase

WHERE Company.name = Product.maker

AND Product.name = Purchase.product

Is this query equivalent to the previous one ?

Beware of duplicates !

Removing Duplicates does deletion of Bud make BudLite

SELECTDISTINCT Company.name

FROM Company, Product

WHERE Company.name= Product.maker

AND Product.name IN

(SELECT Purchase.product

FROM Purchase

SELECTDISTINCT Company.name

FROM Company, Product, Purchase

WHERE Company.name= Product.maker

AND Product.name = Purchase.product

Now

they are

equivalent

Subqueries Returning Relations does deletion of Bud make BudLite

You can also use: s > ALL R

s > ANY R

EXISTS R

Product ( pname, price, category, maker)

Find products that are more expensive than all those produced

By “Gizmo-Works”

SELECT name

FROM Product

WHERE price > ALL (SELECT price

FROM Purchase

WHERE maker=‘Gizmo-Works’)

Correlated Queries does deletion of Bud make BudLite

Movie (title, year, director, length)

Find movies whose title appears more than once.

correlation

SELECTDISTINCT title

FROM Movie AS x

WHERE year < > ANY

(SELECT year

FROM Movie

WHERE title = x.title);

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

Complex Correlated Query does deletion of Bud make BudLite

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, maker

FROM Product AS x

WHERE price > ALL (SELECT price

FROM Product AS y

WHERE x.maker = y.maker AND y.year < 1972);

Existential/Universal Conditions does deletion of Bud make BudLite

Product ( pname, price, company)

Company( cname, city)

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

SELECT DISTINCT Company.cname

FROM Company, Product

WHERE Company.cname = Product.company and Product.price < 100

Existential: easy ! 

Existential/Universal Conditions does deletion of Bud make BudLite

Product ( pname, price, company)

Company( cname, city)

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

Universal: hard ! 

Existential/Universal Conditions does deletion of Bud make BudLite

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

SELECT DISTINCT Company.cname

FROM Company

WHERE Company.cname IN (SELECT Product.companyFROM ProductWHERE Product.price >= 100

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

SELECT DISTINCT Company.cname

FROM Company

WHERE Company.cname NOTIN (SELECT Product.companyFROM ProductWHERE Product.price >= 100

NULLS in SQL does deletion of Bud make BudLite

• 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 ?

Null Values does deletion of Bud make BudLite

• 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

Null Values does deletion of Bud make BudLite

• 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 Person

WHERE (age < 25) AND

(height > 6 OR weight > 190)

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

Null Values does deletion of Bud make BudLite

Unexpected behavior:

Some Persons are not included !

SELECT *

FROM Person

WHERE age < 25 OR age >= 25

Null Values does deletion of Bud make BudLite

Can test for NULL explicitly:

• x IS NULL

• x IS NOT NULL

Now it includes all Persons

SELECT *

FROM Person

WHERE age < 25 OR age >= 25 OR age IS NULL

Outerjoins does deletion of Bud make BudLite

Explicit joins in SQL:

Product(name, category)

Purchase(prodName, store)

Same as:

But Products that never sold will be lost !

SELECT Product.name, Purchase.store

FROM Product JOIN Purchase ON

Product.name = Purchase.prodName

SELECT Product.name, Purchase.store

FROM Product, Purchase

WHERE Product.name = Purchase.prodName

Outerjoins does deletion of Bud make BudLite

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

Product does deletion of Bud make BudLite

Purchase

Outer Joins does deletion of Bud make BudLite

• 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

Aggregation does deletion of Bud make BudLite

SELECT Avg(price)

FROM Product

WHERE maker=“Toyota”

SQL supports several aggregation operations:

SUM, MIN, MAX, AVG, COUNT

Aggregation: Count does deletion of Bud make BudLite

SELECT Count(*)

FROM Product

WHERE year > 1995

Except COUNT, all aggregations apply to a single attribute

Aggregation: Count does deletion of Bud make BudLite

COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)

FROM Product

WHERE year > 1995

Better:

SELECT Count(DISTINCT category)

FROM Product

WHERE year > 1995

Simple Aggregation does deletion of Bud make BudLite

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 Purchase

WHERE product = ‘bagel’

Simple Aggregations does deletion of Bud make BudLite

Purchase

Grouping and Aggregation does deletion of Bud make BudLite

Usually, 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 TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product

Let’s see what this means…

Grouping and Aggregation does deletion of Bud make BudLite

1. Compute the FROM and WHERE clauses.

2. Group by the attributes in the GROUP BY

3. Produce one tuple for every group by applying aggregation

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

First compute the does deletion of Bud make BudLite FROM-WHERE clauses (date > “9/1”) then GROUP BY product:

Then, aggregate does deletion of Bud make BudLite

SELECT product, Sum(price*quantity) AS TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product

GROUP BY v.s. Nested Quereis does deletion of Bud make BudLite

SELECT product, Sum(price*quantity) AS TotalSales

FROM Purchase

WHERE date > “9/1”

GROUP BY product

SELECT DISTINCT x.product, (SELECT Sum(y.price*y.quantity)FROM Purchase yWHERE x.product = y.product AND y.date > ‘9/1’)AS TotalSales

FROM Purchase x

WHERE x.date > “9/1”

Another Example does deletion of Bud make BudLite

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

SELECT product, Sum(price * quantity) AS SumSales

Max(quantity) AS MaxQuantity

FROM Purchase

GROUP BY product

HAVING Clause does deletion of Bud make BudLite

Same query, except that we consider only products that had

at least 30 items sold.

SELECT product, Sum(price * quantity)

FROM Purchase

WHERE date > “9/1”

GROUPBY product

HAVING Sum(quantity) > 30

HAVING clause contains conditions on aggregates.

General form of Grouping and Aggregation does deletion of Bud make BudLite

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 ?

General form of Grouping and Aggregation does deletion of Bud make BudLite

SELECT S

FROM R1,…,Rn

WHERE C1

GROUP BY a1,…,ak

HAVING C2

Evaluation steps:

• Compute the FROM-WHERE part, obtain a table with all attributes in R1,…,Rn

• Group by the attributes a1,…,ak

• Compute the aggregates in C2 and keep only groups satisfying C2

• Compute aggregates in S and return the result

Aggregation does deletion of Bud make BudLite

Document(url, title)

Mentions(url,word)

Grouping vs. Nested Queries does deletion of Bud make BudLite

• Find all authors who wrote at least 10 documents:

• Attempt 1: with nested queries

This isSQL bya novice

SELECTDISTINCT Author.name

FROM Author

Grouping vs. Nested Queries does deletion of Bud make BudLite

• Find all authors who wrote at least 10 documents:

• Attempt 2: SQL style (with GROUP BY)

This isSQL byan expert

SELECT Author.name

FROM Author, Wrote

GROUP BY Author.name

HAVING count(wrote.url) > 10

No need for DISTINCT: automatically from GROUP BY

Grouping vs. Nested Queries does deletion of Bud make BudLite

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

SELECT Author.name

FROM Author, Wrote, Mentions