From Relational Algebra to the Structured Query LanguageReview – Relational IntegrityReview – Relational AlgebraWhy Relational Algebra?Homework Problem 6.18Sets versus BagsWhy Bags? Efficiency!Bag UnionBag IntersectionBag DifferenceBag SelectionBag ProjectionBag Theta-JoinIntroducing SQLRunning Example – The SodaBaseThe Basic SQL QueryExampleSlide 18Select *Slide 20Renaming AttributesSlide 22Expressions in SELECT ClausesSlide 24Slide 25Another Example: ConstantsExample: Complex ConditionsSlide 28Pattern MatchingSlide 30Slide 31Dealing with NullThree-Valued LogicConsiderCombining RelationsTuple VariablesSolutionThe Story Thus FarFrom Relational Algebra to the Structured Query LanguageRose-Hulman Institute of TechnologyCurt CliftonReview – Relational IntegrityEntity Integrity Constraints:Primary key values cannot be nullReferential Integrity Constraints:Foreign key values must either:Match the primary key values of some tuple, orBe nullReview – Relational AlgebraIntersection: R1 R2Union: R1 R2Difference: R1 - R2Selection: BDATE < 1970-1-1 (EMPLOYEE)Projection: FNAME, BDATE(EMPLOYEE)Theta-Join:Natural Join: R1 * R2Why Relational Algebra?Foundational knowledgeUsed by query optimizersFiner grained than SQLCan be formally reasoned aboutFormal basis for semantics of SQLHomework Problem 6.18Parts a–d and gBegin in class, may work in groups of 2–3Please note your partners on the sheetSets versus BagsSetsOrder doesn’t matterNo duplicatesExamples{1,2,3} = {2,1,3}{1,2} {2} = {1,2}Bags (or multi-sets)Order doesn’t matterDuplicates allowedExamples{1,2,3} = {2,1,3}{1,2} {2} = {1,2,2}{1,2,3} ≠ {1,2,2,3}Why Bags? Efficiency!Eliminating duplicates can be expensiveBy default SQL uses bagsBag Union“Just dump all the elements into a single bag”An element appears in the union of two bags the sum of the number of times it appears in each bagBag Intersection“Whichever bag has the fewest, has the answer”An element appears in the intersection of two bags the minimum number of times it appears in either.Bag Difference“Take elements out of the first if they’re in the second”An element appears in the difference of two bags as many times as it appears in the first, minus the number of times it appears in the second, but no less than 0 timesBag SelectionA B1 25 61 2RLike set selectionBut input and output can be bagsBag ProjectionA B1 25 61 2RUnlike set project, can turn a set into a bagBag Theta-JoinA B1 25 61 2RPair each tuple of first table with each tuple of secondCheck conditionDon’t eliminate duplicatesB C3 47 8SIntroducing SQLPronounced:“ess queue ell”Or “sequel”Benefits:Designed for the relational modelEasily optimized by DBMSStandard (well, sort of, a little bit, sometimes)http://sqlfairy.sourceforge.netRunning Example – The SodaBaseSoda(name, manf)Rest(name, addr, contract)Customer(name, addr, phone)Likes(customer, soda)Sells(rest, soda, price)Frequents(customer, rest)The Basic SQL QuerySELECT attributes FROM tableWHERE conditionSemantics: attributes(condition(table))ExampleFind all the names of all sodas made by PepsiCoExampleFind all the names of all sodas made by PepsiCoSELECT name FROM Soda WHERE manf = 'PepsiCo'(note single quotes)Select *For getting all attributes…SELECT *FROM tableWHERE conditionSemantics: condition(table)ExampleSELECT * FROM Soda WHERE manf = 'PepsiCo'Renaming AttributesSELECT attribute1 AS newName1, …FROM tableWHERE conditionSemantics: newName1, …(attribute1, …(condition(table)))ExampleSELECT name AS soda, manf AS makerFROM SodaWHERE manf = 'PepsiCo'Expressions in SELECT ClausesCan use expressions on attributes in SELECTSELECT f(attributes), …FROM tableWHERE conditionMore powerful than the relational algebra we’ve seenWould need functions on tuplesExampleShow selling prices in YenExampleShow selling prices in YenSELECT rest, soda, price * 115 AS priceInYen FROM SellsAnother Example: ConstantsSELECT customer, 'likes Pepsi' AS promotionFROM LikesWHERE soda = 'Pepsi'Example: Complex ConditionsFind the price that Joe’s Sushi charges for PepsiExample: Complex ConditionsFind the price that Joe’s Sushi charges for PepsiSELECT price FROM Sells WHERE rest = 'Joe''s Sushi' AND soda = 'Pepsi'Note:Double apostrophe inside stringAND, OR, NOTCase insensitivePattern MatchingWHERE clauses can compare string to patternAttribute LIKE patternAttribute NOT LIKE patternPattern syntax:Pattern is a string% in string represents any number of characters_ in string represent any single characterExampleFind the customers with exchange 555, regardless of area codeExampleFind the customers with exchange 555, regardless of area codeSELECT name FROM CustomerWHERE phone LIKE '%555-____'-- That’s four underscoresDealing with NullWhy might a tuple have a null value?SQL uses three-valued logic to handle nullA boolean expression can be true, false, or unknownComparison with null yields unknown instead of errorWHERE clause must be true to matchThree-Valued LogicTrue = 1False = 0Unknown = 1/2x AND y = min(x, y)x OR y = max(x, y)NOT x = 1 - xConsiderSELECT restFROM SellsWHERE price < 2.00 OR price >= 2.00If the Sells relation has the value:Beware of nulls!rest soda priceJoe's Pepsi nullCombining RelationsList multiple tables in FROMUse Relation.Attribute to distinguishSELECT sodaFROM Likes, FrequentsWHERE Frequents.customer = Likes.customerAND rest = 'Joe''s'Semantics:Tuple VariablesCan distinguish two copies of same relationExample: Find all pairs of sodas by the same manufacturer…Omitting trivial pairs like (Pepsi, Pepsi)Omitting permutations of same sodas by listing members of pair alphabeticallySolutionSELECT s1.name, s2.nameFROM Soda s1, Soda s2WHERE s1.manf = s2.manfAND s1.name < s2.nameThe Story Thus FarSELECT … FROM … WHERESELECT * …SELECT Foo AS Bar …SELECT expression …SELECT … FROM … WHERE … LIKE …SELECT … FROM Foo, Bar …SELECT … FROM Foo f1, Foo f2
View Full Document