prof. sin-min lee

91

Upload: louie

Post on 24-Feb-2016

34 views

Category:

Documents


1 download

DESCRIPTION

Final Revision 3. CS 157B Lecture 23. Prof. Sin-Min Lee. Modeling. A database can be modeled as: a collection of entities, relationship among entities. An entity is an object that exists and is distinguishable from other objects. Example: specific person, company, event, plant - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Prof. Sin-Min Lee
Page 2: Prof. Sin-Min Lee

Modeling• A database can be modeled as:

– a collection of entities,– relationship among entities.

• An entity is an object that exists and is distinguishable from other objects.– Example: specific person, company, event, plant

• Entities have attributes– Example: people have names and addresses

• An entity set is a set of entities of the same type that share the same properties.– Example: set of all persons, companies, trees, holidays

Page 3: Prof. Sin-Min Lee

Entity Sets customer and loancustomer_id customer_ customer_ customer_ loan_ amount name street city number

Page 4: Prof. Sin-Min Lee

Relationship Sets• A relationship is an association among several entitiesExample:Hayesdepositor A-102customer entityrelationship setaccount entity

• A relationship set is a mathematical relation among n 2 entities, each taken from entity sets{(e1, e2, … en) | e1 E1, e2 E2, …, en En}

where (e1, e2, …, en) is a relationship– Example:

(Hayes, A-102) depositor

Page 5: Prof. Sin-Min Lee

Relationship Set borrower

Page 6: Prof. Sin-Min Lee

Relationship Sets (Cont.)• An attribute can also be property of a relationship set.• For instance, the depositor relationship set between entity sets

customer and account may have the attribute access-date

Page 7: Prof. Sin-Min Lee

Degree of a Relationship Set• Refers to number of entity sets that participate in a relationship set.• Relationship sets that involve two entity sets are binary (or degree

two). Generally, most relationship sets in a database system are binary.• Relationship sets may involve more than two entity sets.

• Relationships between more than two entity sets are rare. Most relationships are binary. (More on this later.)

Example: Suppose employees of a bank may have jobs (responsibilities) at multiple branches, with different jobs at different branches. Then there is a ternary relationship set between entity sets employee, job, and branch

Page 8: Prof. Sin-Min Lee

Composite Attributes

Page 9: Prof. Sin-Min Lee

Mapping Cardinality Constraints

• Express the number of entities to which another entity can be associated via a relationship set.

• Most useful in describing binary relationship sets.• For a binary relationship set the mapping cardinality must be one

of the following types:– One to one– One to many– Many to one– Many to many

Page 10: Prof. Sin-Min Lee

Mapping Cardinalities

One to one One to many

Note: Some elements in A and B may not be mapped to any elements in the other set

Page 11: Prof. Sin-Min Lee

Mapping Cardinalities

Many to one Many to many

Note: Some elements in A and B may not be mapped to any elements in the other set

Page 12: Prof. Sin-Min Lee

Keys• A super key of an entity set is a set of one or more attributes whose values uniquely determine each entity.

• A candidate key of an entity set is a minimal super key– Customer_id is candidate key of customer– account_number is candidate key of account

• Although several candidate keys may exist, one of the candidate keys is selected to be the primary key.

Page 13: Prof. Sin-Min Lee

Keys for Relationship Sets• The combination of primary keys of the participating entity sets forms a super key of a relationship set.– (customer_id, account_number) is the super key of depositor– NOTE: this means a pair of entity sets can have at most one

relationship in a particular relationship set. • Example: if we wish to track all access_dates to each

account by each customer, we cannot assume a relationship for each access. We can use a multivalued attribute though

• Must consider the mapping cardinality of the relationship set when deciding what are the candidate keys

• Need to consider semantics of relationship set in selecting the primary key in case of more than one candidate key

Page 14: Prof. Sin-Min Lee

E-R Diagrams

Rectangles represent entity sets. Diamonds represent relationship sets. Lines link attributes to entity sets and entity sets to relationship sets. Ellipses represent attributes

Double ellipses represent multivalued attributes. Dashed ellipses denote derived attributes.

Underline indicates primary key attributes (will study later)

Page 15: Prof. Sin-Min Lee

E-R Diagram With Composite, Multivalued, and Derived Attributes

Page 16: Prof. Sin-Min Lee

Relationship Sets with Attributes

Page 17: Prof. Sin-Min Lee

Roles• Entity sets of a relationship need not be distinct• The labels “manager” and “worker” are called roles; they specify how

employee entities interact via the works_for relationship set.• Roles are indicated in E-R diagrams by labeling the lines that connect

diamonds to rectangles.• Role labels are optional, and are used to clarify semantics of the

relationship

Page 18: Prof. Sin-Min Lee

Cardinality Constraints• We express cardinality constraints by drawing either a directed line (), signifying “one,” or an undirected line (—), signifying “many,” between the relationship set and the entity set.

• One-to-one relationship:– A customer is associated with at most one loan via the relationship

borrower– A loan is associated with at most one customer via borrower

Page 19: Prof. Sin-Min Lee

One-To-Many Relationship

• In the one-to-many relationship a loan is associated with at most one customer via borrower, a customer is associated with several (including 0) loans via borrower

Page 20: Prof. Sin-Min Lee

Many-To-One Relationships

• In a many-to-one relationship a loan is associated with several (including 0) customers via borrower, a customer is associated with at most one loan via borrower

Page 21: Prof. Sin-Min Lee

Many-To-Many Relationship• A customer is associated with several (possibly 0) loans via borrower• A loan is associated with several (possibly 0) customers via borrower

Page 22: Prof. Sin-Min Lee

Participation of an Entity Set in a Relationship Set

Total participation (indicated by double line): every entity in the entity set participates in at least one relationship in the relationship set E.g. participation of loan in borrower is total

every loan must have a customer associated to it via borrower Partial participation: some entities may not participate in any relationship in

the relationship set Example: participation of customer in borrower is partial

Page 23: Prof. Sin-Min Lee

Alternative Notation for Cardinality Limits

Cardinality limits can also express participation constraints

Page 24: Prof. Sin-Min Lee

E-R Diagram with a Ternary Relationship

Page 25: Prof. Sin-Min Lee

Cardinality Constraints on Ternary Relationship

• We allow at most one arrow out of a ternary (or greater degree) relationship to indicate a cardinality constraint

• E.g. an arrow from works_on to job indicates each employee works on at most one job at any branch.

• If there is more than one arrow, there are two ways of defining the meaning. – E.g a ternary relationship R between A, B and C with arrows to B and C

could mean 1. each A entity is associated with a unique entity from B and C or 2. each pair of entities from (A, B) is associated with a unique C entity, and each pair (A, C) is associated with a unique B

– Each alternative has been used in different formalisms– To avoid confusion we outlaw more than one arrow

Page 26: Prof. Sin-Min Lee

Binary Vs. Non-Binary Relationships

• Some relationships that appear to be non-binary may be better represented using binary relationships– E.g. A ternary relationship parents, relating a child to

his/her father and mother, is best replaced by two binary relationships, father and mother

• Using two binary relationships allows partial information (e.g. only mother being know)

– But there are some relationships that are naturally non-binary

• Example: works_on

Page 27: Prof. Sin-Min Lee

Converting Non-Binary Relationships to Binary Form

• In general, any non-binary relationship can be represented using binary relationships by creating an artificial entity set.– Replace R between entity sets A, B and C by an entity set E, and three relationship

sets: 1. RA, relating E and A 2.RB, relating E and B

3. RC, relating E and C– Create a special identifying attribute for E– Add any attributes of R to E – For each relationship (ai , bi , ci) in R, create

1. a new entity ei in the entity set E 2. add (ei , ai ) to RA

3. add (ei , bi ) to RB 4. add (ei , ci ) to RC

Page 28: Prof. Sin-Min Lee

Converting Non-Binary Relationships (Cont.)

• Also need to translate constraints– Translating all constraints may not be possible– There may be instances in the translated schema that

cannot correspond to any instance of R• Exercise: add constraints to the relationships RA, RB and RC to

ensure that a newly created entity corresponds to exactly one entity in each of entity sets A, B and C

– We can avoid creating an identifying attribute by making E a weak entity set (described shortly) identified by the three relationship sets

Page 29: Prof. Sin-Min Lee

Mapping Cardinalities affect ER Design Can make access-date an attribute of account, instead of a relationship

attribute, if each account can have only one customer That is, the relationship from account to customer is many to one, or

equivalently, customer to account is one to many

Page 30: Prof. Sin-Min Lee

Weak Entity Sets• An entity set that does not have a primary key is referred to as a weak

entity set.• The existence of a weak entity set depends on the existence of a

identifying entity set– it must relate to the identifying entity set via a total, one-to-many

relationship set from the identifying to the weak entity set– Identifying relationship depicted using a double diamond

• The discriminator (or partial key) of a weak entity set is the set of attributes that distinguishes among all the entities of a weak entity set.

• The primary key of a weak entity set is formed by the primary key of the strong entity set on which the weak entity set is existence dependent, plus the weak entity set’s discriminator.

Page 31: Prof. Sin-Min Lee

Weak Entity Sets (Cont.)

• We depict a weak entity set by double rectangles.• We underline the discriminator of a weak entity set with a dashed line.• payment_number – discriminator of the payment entity set • Primary key for payment – (loan_number, payment_number)

Page 32: Prof. Sin-Min Lee

Weak Entity Sets (Cont.)

• Note: the primary key of the strong entity set is not explicitly stored with the weak entity set, since it is implicit in the identifying relationship.

• If loan_number were explicitly stored, payment could be made a strong entity, but then the relationship between payment and loan would be duplicated by an implicit relationship defined by the attribute loan_number common to payment and loan

Page 33: Prof. Sin-Min Lee

More Weak Entity Set Examples• In a university, a course is a strong entity and a course_offering can be

modeled as a weak entity• The discriminator of course_offering would be semester (including year)

and section_number (if there is more than one section)• If we model course_offering as a strong entity we would model

course_number as an attribute. Then the relationship with course would be implicit in the course_number attribute

Page 34: Prof. Sin-Min Lee

Extended E-R Features: Specialization

• Top-down design process; we designate subgroupings within an entity set that are distinctive from other entities in the set.

• These subgroupings become lower-level entity sets that have attributes or participate in relationships that do not apply to the higher-level entity set.

• Depicted by a triangle component labeled ISA (E.g. customer “is a” person).

• Attribute inheritance – a lower-level entity set inherits all the attributes and relationship participation of the higher-level entity set to which it is linked.

Page 35: Prof. Sin-Min Lee

Specialization Example

Page 36: Prof. Sin-Min Lee

Extended ER Features: Generalization

• A bottom-up design process – combine a number of entity sets that share the same features into a higher-level entity set.

• Specialization and generalization are simple inversions of each other; they are represented in an E-R diagram in the same way.

• The terms specialization and generalization are used interchangeably.

Page 37: Prof. Sin-Min Lee

Specialization and Generalization (Cont.)

• Can have multiple specializations of an entity set based on different features.

• E.g. permanent_employee vs. temporary_employee, in addition to officer vs. secretary vs. teller

• Each particular employee would be – a member of one of permanent_employee or

temporary_employee, – and also a member of one of officer, secretary, or teller

• The ISA relationship also referred to as superclass - subclass relationship

Page 38: Prof. Sin-Min Lee

Design Constraints on a Specialization/Generalization

• Constraint on which entities can be members of a given lower-level entity set.– condition-defined

• Example: all customers over 65 years are members of senior-citizen entity set; senior-citizen ISA person.

– user-defined• Constraint on whether or not entities may belong to more than one

lower-level entity set within a single generalization.– Disjoint

• an entity can belong to only one lower-level entity set• Noted in E-R diagram by writing disjoint next to the ISA

triangle– Overlapping

• an entity can belong to more than one lower-level entity set

Page 39: Prof. Sin-Min Lee

Design Constraints on a Specialization/Generalization (Cont.)

• Completeness constraint -- specifies whether or not an entity in the higher-level entity set must belong to at least one of the lower-level entity sets within a generalization.– total : an entity must belong to one of the lower-level entity sets– partial: an entity need not belong to one of the lower-level entity

sets

Page 40: Prof. Sin-Min Lee

Aggregation

Consider the ternary relationship works_on, which we saw earlier

Suppose we want to record managers for tasks performed by an employee at a branch

Page 41: Prof. Sin-Min Lee

E-R Diagram for a Banking Enterprise

Page 42: Prof. Sin-Min Lee

Summary of Symbols Used in E-R Notation

Page 43: Prof. Sin-Min Lee

Summary of Symbols (Cont.)

Page 44: 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))

Page 45: Prof. Sin-Min Lee

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 46: Prof. Sin-Min Lee

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 47: Prof. Sin-Min Lee

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 48: Prof. Sin-Min Lee

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 49: Prof. Sin-Min Lee

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 50: Prof. Sin-Min Lee

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 51: Prof. Sin-Min Lee

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 52: Prof. Sin-Min Lee

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 53: Prof. Sin-Min Lee

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 54: Prof. Sin-Min Lee

ExampleWhat beers are made by Anheuser-Busch?

Beers(name, manf)

SELECT nameFROM BeersWHERE manf = 'Anheuser-Busch';

• Note: single quotes for strings.nameBudBud LiteMichelob

Page 55: Prof. Sin-Min Lee

Union, Intersection, Difference(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 56: Prof. Sin-Min Lee

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 57: Prof. Sin-Min Lee

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 58: Prof. Sin-Min Lee

Renaming columns

Beers(name, manf)

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

beerBudBud LiteMichelob

Page 59: Prof. Sin-Min Lee

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 60: Prof. Sin-Min Lee

• 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 61: Prof. Sin-Min Lee

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

Sells(bar, beer, price)

SELECT priceFROM SellsWHERE bar = 'Joe''s Bar' ANDbeer = '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 62: Prof. Sin-Min Lee

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 63: Prof. Sin-Min Lee

Modifying the Database

Three kinds of modifications• Insertions• Deletions• Updates

Sometimes they are all called “updates”

Page 64: Prof. Sin-Min Lee

Deleting or Modifying a TableDeleting:

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; Example: Exercise with care !!

Page 65: Prof. Sin-Min Lee

Default ValuesSpecifying 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

Page 66: Prof. Sin-Min Lee

Conserving Duplicates

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

UNION ALL

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

Page 67: Prof. Sin-Min Lee

InsertionsGeneral form:

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

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

Example: Insert a new purchase to the database:

Page 68: Prof. Sin-Min Lee

Insertions

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 69: Prof. Sin-Min Lee

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)

Purchasecorrupted

Page 70: Prof. Sin-Min Lee

Insertion: an ExampleINSERT INTO Product(name)

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

name listPrice category

gizmo 100 Gadgets

camera - -

Page 71: Prof. Sin-Min Lee

Insertion: an Example

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 72: Prof. Sin-Min Lee

Deletions

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 73: Prof. Sin-Min Lee

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 74: Prof. Sin-Min Lee

Updates

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

Example:

Page 75: Prof. Sin-Min Lee

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 76: Prof. Sin-Min Lee

Examplebar beer priceJoe'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 77: Prof. Sin-Min Lee

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' ANDFrequents.drinker = Likes.drinker;

Page 78: Prof. Sin-Min Lee

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' ANDbeer = 'Bud');

• Notice the scoping rule: an attribute refers to the most closely nested relation with that attribute.

• Parentheses around subquery are essential.

Page 79: Prof. Sin-Min Lee

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 80: Prof. Sin-Min Lee

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 81: Prof. Sin-Min Lee

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 82: Prof. Sin-Min Lee

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 83: Prof. Sin-Min Lee

Example

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

SELECT DISTINCT priceFROM Sells;

Page 84: Prof. Sin-Min Lee

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 85: Prof. Sin-Min Lee

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 86: Prof. Sin-Min Lee

Eliminating DuplicatesBefore Aggregation

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

Sells(bar, beer, price)

SELECT COUNT(DISTINCT price)FROM SellsWHERE beer = 'Bud';• DISTINCT may be used in any aggregation,

but typically only makes sense with COUNT.

Page 87: Prof. Sin-Min Lee

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 88: Prof. Sin-Min Lee

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 89: Prof. Sin-Min Lee

Restriction on SELECT Lists With AggregationIf 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 90: Prof. Sin-Min Lee

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 91: Prof. Sin-Min Lee

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