Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define…...

34
Relational Algebra CS 4750 – Database Systems 1

Transcript of Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define…...

Page 1: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Relational AlgebraCS 4750 – Database Systems

1

Page 2: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Why Relational Algebra?

´ Relational Algebraisthemathematical foundation forhowwedefinerelationships andgetdata inandoutofthesystem

´ Doeseveryquerylanguage (e.g.SQL)followRelational Algebra?No!

´ Someexamples…´EasytodoinRA

´VeryhardinSQL

2

Page 3: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Relational Algebra

´ UnaryOperations

´Selection:σ´Project:π´Rename:ρ

Anoperatortakesone(unary)ortwo(binary)relations asinputandreturnsanewsingle relationasoutput

´ BinaryOperations

´Union:U

´Setdifference:−´Cartesian product: ×

´ Sixfundamental operations:

3

Page 4: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Relational Algebra´ Basedonthesixfundamentaloperationswecandefine…´ Additionalrelationaloperations(addnoadditional‘power’)

´ Setintersection:∩´ Naturaljoin: ⋈

´ Division:÷´ Assignment:←

´ Extendedoperations(withadditionalexpressiveness)´ AggregatefunctionG

´ Outerjoin

4

Page 5: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Selection (σ) – Sigma

´ σp(r), wherep =selection predicate,r=relation(table)

´ Comparisons intheselection predicate:=, <, ≤, >, ≥, ≠´Comparisonsarenotonlybetweenanattributeandavalue,butmayalsobeacomparisonbetweentwoattributes

´ Combining severalpredicates intoalargerpredicatecanbedonebyusingtheconnectives: AND,OR,andNOT

´ Selects specific tuples (rows)fromarelation (table)

´ Limits therowsbased onwhatwe’relookingfor

5

Page 6: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Selection (σ)

´σcity = “Zurich” AND postcode > 8010 (customer)´ “Findalltuples inthecustomerrelationthatareinthecityofZurichand

haveapostcode greaterthan8010.”

´ Result?

6

CD store Relational Database example © B.Signer

Page 7: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Selection (σ)

´ !!!Attention !!!

´ Theselection operation inrelational algebrahasadifferent meaningthattheSELECT statement used inSQL´SELECTinSQLcorrespondstoaprojection inrelationalalgebra

´Wewilltalkaboutprojectionnext

7

Page 8: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Selection (SQL) == Projection (RA)8

´ Example: ThetableE(forEMPLOYEE)

Page 9: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Projection (π) – Pi

´ πA1, A2, …, Am (r), whereAi =attribute

´ Returnspecificattributes (columns)fromarelation

´ Identical tuplescollapse intoasingle tuple(duplicates removed)intheresulting relation

9

Page 10: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Projection (π) – Pi

Identical tuplescollapse intoasingle tuple(duplicates removed)intheresulting relation

10

Page 11: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Rename (ρ) – Rho

´ ρx(E), renames theresultofexpression Etox

´ ρx(A1, A2, …, An)(E), renamestheresultofexpression Etoxandrenames theattributes toA1, A2, …, An

´ρperson(name, location) (πname, city (customer))

11

CD store Relational Database example © B.Signer

Page 12: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Union (U)

´ r U s, whererandsaretworelations´ Unify(combine)tuples fromtworelations

´ Twothingsmust apply´ randsmusthavethesamedegree(samenumberofattributes)

´Thecorrespondingattributedomainsmusthaveacompatibletype

´ “Or”:“FindthenamesofSailorswhorentedaGreenor Redboat”

12

Page 13: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Intersect (∩)

´ r ∩ s, whererandsaretworelations´ Unify(combine)tuples thatarepresent inbothrelations

´ SamerulesforUnionmustapply

´ Union(U)is“or”

´ Intersect(∩)is“and”

´ “And”:“Findthenames ofpeople living inVirginiaandwhoownahome”

13

Page 14: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Set Difference (−)

´ r − s, whererandsaretworelations´ Findthetuplesthatareinonerelationbutarenotinanother

´ Twothingsmust apply´ randsmusthavethesamedegree(samenumberofattributes)

´Thecorrespondingattributedomainsmusthaveacompatibletype

´ πname (supplier) − πname (customer)´ “Findthenamesofsupplierswhoarenotcustomers”

14

Page 15: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Cartesian (Cross) Product (×)

´ r × s, whererandsaretworelations´ Combines informationfromanytwotables

´ Schemaoftheresult isthecombinedschemas ofthetworelations´Relation1has3attributes

´Relation2has4attributes

´TheresultingrelationaftercombiningthetwotablesusingtheCartesianproductwillhave7attributes

´Theattributesofthe1st relationfollowedbytheattributesofthe2nd

15

Page 16: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Cartesian Product (×)

´ Question: Customerwhoate>1itemfromthemenu

´ Crossatablewithitself, canrenameoneofthetables

´ MatchwhereC1 =C2 andD1 ≠ D2

´ So,customerAnnate>1dish

16

Customer Dish

Ann Chicken

Bob Fish

Ann Veal

EatLog

C1 D1 C2 D2

Ann Ch Ann Ch

Ann Ch Bob Fi

Ann Ch Ann Ve

Bob Fi Ann Ch

Bob Fi Bob Fi

Bob Fi Ann Ve

Ann Ve Ann Ch

Ann Ve Bob Fi

Ann Ve Ann Ve

EatLogxEatLog

à

à

Page 17: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Cartesian Product (×) Example17

A B Ca b cd a fc b d

D E Fx y zp q r

A B C D E Fa b c x y za b c p q rd a f x y zd a f p q rc b d x y zc b d p q r

R

S

R × SNote: RxS is not the same as SxR!

Page 18: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Natural Join (⋈) (“Inner Join”)

´ r ⋈ s = πR US (σr.A1=s.A1 ^ r.A2=s.A2 ^ … ^ r.An=s.An (r x s))´ whereR U S = {A1, A2, …, An}´ Takethecrossproductoftwotables, select therowsyoucareabout

´ Binaryoperation

´ Combine certainSELECTIONSandaCARTESIANPRODUCTintooneoperation´FormsaCartesianproductofitstwoarguments

´Performsaselectionforcingequalityonthoseattributesthatappearinbothrelationschemas

´Removesduplicates

18

Page 19: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Natural Join (⋈) (“Inner Join”)

´r ⋈ s = πR US (σr.A1=s.A1 ^ r.A2=s.A2 ^ … ^ r.An=s.An (r x s))

´ Natural joinisanassociative operation

´ Usedquiteoften!

19

It performs a PROJECTION on the unionof all the attributes of both relations

It forms a SELECTION on tuples with equal, similarly named attributes

That is, keep all tuples of the cartesian product r x s that have the same value for the shared attributes or r(R) and s(S)

Page 20: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Natural Join (⋈) Example20

A B Ca b cd b cb b fc a d

B C Db c db c ea d b

A B C Da b c da b c ed b c dd b c ec a d bR

S

R ⋈ S

TheNaturalJoineliminatesreplicatedattributes(e.g.columns“B”and“C”showuponlyonceintheR ⋈ S table.)

Page 21: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Outer Join

´ Leftouter join:=⋈ (mostcommon)– discussed next

´ Rightouterjoin:⋈=´ Fullouter join:=⋈= (mostuncommon)

´ Extensions ofthenaturaljoinoperation

´ Computes thenaturaljoinandthenaddsthetuples fromonerelationthatdonotmatchtheotherrelation

´ Padsthetupleswithnullvalues

21

Page 22: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Outer Join

´ r1 =⋈ r2 Example – Leftouterjoin

´ Takes alltuples inthe left relation (r1)thatdidnotmatch withanytupleintheright relation(r2),padsthetupleswithnullvaluesforallotherattributes fromtheright relation(r2),andaddsthemtotheresultofthenaturaljoin

´ Want: List of all customers with their ordersYou want to know if you have any customers who still haven’t placed any orders yet. So you need ALL of the rows from the left relation r1 (ALL customer names) but you might not need all of the rows from relation r2

22

Name C_id …… … …

Name Order# Items …… … … …

Customers Table (r1) Orders Table (r2)

Page 23: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Outer Join´ Giventhefollowingexample “CDStore”Database

23

CD store Relational Database example © B.Signer

Page 24: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Outer Join24

CD store Relational Database example © B.Signer

Page 25: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Outer Join

´ Leftouter join

´ customer =⋈ order´ Result: (nullscomefromtherelation onthe⋈ side- order)

´ (Inorder table,customers“53”and“2”madepurchases)

25

Page 26: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Assignment (←)

´ v← E´ Theexpression (E)ontheRHSoftheassignment operatorisassigned

temporarily totherelation variable(v)ontheLHS

Temp1 ={someexpression}

Temp2 ={someotherexpression}

Result =Temp1 UTemp2

26

Page 27: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

27

Page 28: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Division (÷)

´ r ÷ s´ Wheresisasubset ofr

´ “Forall”queries

´ “AB÷ B” Find“A”forall“B”,where“A”and“B”areattributes

´ (AllA’spairedwiththeirB’s)÷ (Allpossible B’s)

“AB”set ÷ “B”set

Result: ListofA’s

28

Page 29: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Division (÷)

´ Exampler ÷ s

29

Page 30: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Aggregate Function (G)

´G1, G2, …, Gm G F1(A1), F2(A2), …, Fn(An) (R)´ Where

´Gn =attributesonwhichtogroup,

´Fi =aggregatefunctionsonanattribute (An),

´R=relation

´ Theaggregatefunctions canbe:´Min,max,sum,count,average

´ Countofnumberofsailors: G count(sid) (Sailors)´ Result isarelation,singlecolumn: Sidwithresult value

30

Page 31: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Aggregate Function (G)

´ “Numberofeachofthecolorsoftheboats”

´ Countofnumberofboats,groupedbycolor:

colorG count(bid) (Boats)

31

color count(bid)Red 2Blue 1

Yellow 1Green 1

Page 32: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

Aggregate Function (G)

´ Justaddcommastoincludemultiple groupingcolums

´ E.g.UsingBankDatabase

´ branch-nameG sum(amount), max(amount) (loan)

32

branch-name sum(amount) max(amount)Downtown 2500 1500Perryridge 2800 1500

Page 33: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

33

Page 34: Relational Algebra...Relational Algebra ´ Based on the six fundamental operations we can define… ´ Additional relational operations (add no additional ‘power’) ´ Set intersection:

34