Published on

Introduction to database lecture# 6: This lecture is all about Nested Structure in Database

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. SQL1Fall 2001 Database Systems 1Nested StructuresSELECT NameFROM ItemsWHERE Iid IN (SELECT DISTINCT Iid FROM Bids) ¢¡¤£¦¥¨§  © ¨© !!#%$#© ¢)( ( 02143)5 6%7 89!7A@49BC C DFE G¢G%E BIH8¦E P QRF9¢S47#@49BT C UV6V5 6¢7!1A9¢G#6 WX6%Y`V9%P4a¢b T c9%dGA3#7A7 DV35 53 #7e b f g#9¢S!Ph9i#p%qg%E 1A3#7A7A90)6¢3¢@I@¢5 6r ( g%E G#6 89!7A@49BstVuXv s2w x uXy%€! t¦w x sV‚!ƒtx „†…†‡‚ˆ#€‰¦ ‘2’ “”•– —V’ ˜ ’4™‰¦ ‘2˜ “”•– —%d ™ e2™‰¦ ‘¦• “”•¦’ —V’ d ’4“‰¦ ‘d f)”)’ —e ™ gh™‰¦ ‘¦™ f)”)’ —V’ ˜ ˜–‰¦ ‘Ve f)”)˜ —%d • gV–‰¦ ‘)g f)”)˜ —V˜ ’ d‰¦ ‘¦“ f)”• —V˜ • ™Fall 2001 Database Systems 2Let Temp = SELECT Iid FROM Bids i†j¦kml nVo pq¦rqsqVtq¦uSELECT Name FROM Items WHERE Iid IN (SELECT Iid FROM Bids)Is Iid IN Temp?Is I1 IN Temp?v!wFxy{z v| } ~¨| } X€%‚ ƒ!„!…#€¢†#| „¢‡ˆ)‰ ‰ Š2‹4Œ Ž¢ %‘!A’ ‘“Pick a tuple from ItemsYES!Put this tuple in the outputv!wFxy{z v| } ~¨| } X€%‚ ƒ!„!…#€¢†#| „¢‡ˆ” ” •¤– —!—%– “4˜™š ›¤‘¢œAA’I‘“Is Iid IN Temp?Is I2 IN Temp?Pick another tuple from ItemsYES!Put this tuple in the outputv!wFxy{z v| } ~¨| } X€%‚ ƒ!„!…#€¢†#| „¢‡ˆ ” ž)Ž) Ž¢#‹4‘%—AŽ ŸX Is Iid IN Temp?Is I3 IN Temp?Pick another tuple from ItemsNO!Remove this tuple fromthe output
  2. 2. SQL2Fall 2001 Database Systems 3Nested Structures – correlationSELECT I.Name FROM Items IWHERE I.Iid IN (SELECT DISTINCT B.Iid FROM Bids BWHERE B.Buyid = I.Oid) ¢¡¤£¦¥¨§  © © !¢¢#$%$© (0) ) 132546 78 9@¢8BA @CPick a tuple from ItemsCompute thenested relationDFEHGPI Q¤R ST UIs I1 in Temp? No, remove this tuple!V¢W¤X¦Y¨` Va b ca b def g h¢i¢p$eq$a irs¦t t uwv x¢xv y5€‚¦ƒ „w…†B‡Bˆ‰…yPick a tuple from ItemsCompute thenested relation’‘H“•” –¤— ˜™ dIs I2 in Temp? No, remove this tuple!Fall 2001 Database Systems 4Nested Structures – correlationSELECT I.Name FROM Items IWHERE I.Iid IN (SELECT DISTINCT B.Iid FROM Bids BWHERE B.Buyid = I.Oid)e$f¤g0hi ej k lmj k nopq r¢s¢t$ou$j svw¦x y z0{0| {}$~5€B{ {‚Fƒ3„Pick a tuple from ItemsCompute thenested relation…’†H‡•ˆ ‰¤Š ‹Œ Is I3 in Temp? No, remove this tuple!Ž¢¤¦‘¨’ Ž“ ” •H“ ” –¤—˜™ š¢›$œ$—$$“ ›¢žŸ  ¡ ¢£¢¤¤¥$¦$§‰§ ¨©¦ª ª¦ B§Pick a tuple from ItemsCompute thenested relation«’¬ ­P® ¯¤° ±²´³²µIs I4 in Temp? YES, keep this tuple!
  3. 3. SQL3Fall 2001 Database Systems 5SQL - Nested Statements• A nested sub-expression may refer to the tuples from the outerrelationSELECT Buy.NameFROM Buyers BuyWHERE Buy.BuyId IN (SELECT B.BuyIDFROM Bids BWHERE B.Amount 20 ANDB.BuyID NOT IN (SELECT B2.BuyIDFROM Bids B2WHERE B2.Amount = 20AND B2.Iid = B.Iid))Names of buyers with a bidgreater than 20 on an itemfor which the buyer has noother bids less than 20.Fall 2001 Database Systems 6Nested Structures - ExistsSELECTFROMWHERE (NOT) EXISTS(SELECT *FROM R1, ..., RmWHERE P)• Semantics: For each tuple of the outer query, executethe inner query; if there is at least one (no) tuple in theresult of the inner query, then retrieve that tuple of theouter query.• This accounts for the “there exists” type of queries
  4. 4. SQL4Fall 2001 Database Systems 7SQL Nested Statements• Two more nested conditions:– EXISTS ( SELECT … FROM … WHERE … ) is true if theSFW clause returns a non-empty relation– NOT EXISTS ( SELECT … FROM … WHERE … ) is true ifthe SFW clause returns an empty relation• Find the name of all buyers who have no bids with an amount lessthan 50SELECT Buy.NameFROM Buyers BuyWHERE NOT EXISTS (SELECT B.BuyIdFROM Bids BWHERE B.Amount 50 ANDB.BuyID=Buy.BuyId)Fall 2001 Database Systems 8SQL - EXISTS• Find the names of buyers who placed a bid onall items with one or more bidsSELECT Buy.NameFROM Buyers BuyWHERE EXISTS (SELECT B.IidFROM Bids BWHERE Buy.BuyId = B.BuyId)Is this correct?Names of buyers whohave bid on an itemFind buyers such that there does not exist anitem with bids on which these buyers did not bid
  5. 5. SQL5Fall 2001 Database Systems 9SQL - EXISTS• Find the names of buyers who placed a bid on all itemswith one or more bidsSELECT Buy.NameFROM Buyers BuyWHERE NOT EXISTS (SELECT B.IidFROM Bids BWHERE NOT EXISTS (SELECT *FROM Bids B2WHERE B.Iid = B2.Iid ANDB2.Buyid = Buy.BuyId) )bids for this itemby this buyeritems with bids, butnot by this buyereither there are no bidsor this buyer has a bidon everythingFall 2001 Database Systems 10Things to Think About• Don’t use nested queries if they are notneeded.– they make the query unnecessarilycomplicated– they make optimization harder• If a query requires only “IN” and “EXISTS”,then it probably can be done without nesting.
  6. 6. SQL6Fall 2001 Database Systems 11Aggregate functions• Count, Max, Min, Sum, and Avg are aggregate functionsthat apply to the values of a set of tuples• Find the total number of bids in the bids tableSELECT Count(*)FROM Bids• Find the average bid for the “Dipping Bird”.SELECT Avg(B.Amount) AS AvgAmtFROM Bids B, Items IWHERE B.Iid = I.Iid AND I.Name = ‘Dipping Bird’Fall 2001 Database Systems 12Aggregate Functions• Find the buyer(s) who placed the maximum bid on the “DippingBird”SELECT DISTINCT B2.BuyidFROM Bids B2, Items I2WHERE B2.Iid=I2.Iid ANDI2.Name = ‘Dipping Bird’ ANDB2.Amount = (SELECT Max(B.Amount)FROM Bids B, Items IWHEREB.Iid = I.Iid ANDI.Name = ‘Dipping Bird’)
  7. 7. SQL7Fall 2001 Database Systems 13GroupingSELECT aFROM bWHERE cGROUP BY dCreate the Cartesian product of the relations in bFind all tuples from the Cartesian product that satisfy the condition in c(including any subexpressions)For all distinct values of the columns listed in d, create a group thatcontains the set of tuples with that value for “d”Create the columns in a, which should start with columns in d and endwith aggregates that will apply to each group separately.Fall 2001 Database Systems 14Group by• Find the average bid amount for each item, listthe item name, the average bid and the numberof bidsSELECT I.name,avg(B.Amount) AS AvgBid,count(*) AS CntFROM Items I, Bids BWHERE I.Iid = B.IidGROUP BY I.name
  8. 8. SQL8Fall 2001 Database Systems 15 ¢¡¤£ ¥§¦ ¨ © ¦ ¨ ¥¢ !¨ $#%¤( )0¦ ¨ 123# 4¤%¤5¤ ¦ %!687 9§@ A¢BC3D E@ 68F @HG IP@ QRTSU VW 63X¤WTYX3`687 9§F A¢BC3D E!a 6G b8G IcC dXegf S(W(W hiS!U US W687 98C A¢BC8@ E@ 63a @HA IP@ QRTSU VW 63X¤WTYX3`687 9¢a pB!@ E3b 6G q§G IP@ r7 f V 63X¤WTYX3`687 98G pB!@ E@ 68F F!D IP@ QRTSU VW 63X¤WTYX3`687 9b pB!F E!a 63a qD IcC dXegf S(W(W hiS!U US W687 9¢q pB!F EF 68@ a IPF h$7 f¤f!7 `tsu6 vwXx WTYX3`687 98A pBC EF 6C G IPF h$7 f¤f!7 `tsu6 vwXx WTYX3`First Step• After the FROM/WHERE clause before groupingFall 2001 Database Systems 16y€ ‚$ƒ „†…‡§ˆ ‰ƒ y‘ ƒt’ “”ƒ •—–˜†™ de y8f¢e3g(f§hy€ ‚‡ „†…‡ƒ ‰ƒ y†i ƒ„ “”ƒ •—–˜†™ de y8f¢e3g(f§hy€ ‚i’ j…§ƒ ‰ƒ y‘ ‘8ˆ “”ƒ •—–˜†™ de y8f¢e3g(f§hkl m†n op8q rq ks t uwv x2y zz8y {¤|~} c€8!‚!ƒ(€†{}y „i… †‡ˆ ‰v }iˆ Š uwv x2y zz8y {¤|~} c€8!‚!ƒ(€†{‹Œ $Ž †¢‘§’ “¢” ‹†• –i• —˜‘ ™š¢›œž!ŸŸ  $ž†¡ ¡ž 3Ÿ‹Œ – ¢Ž “¢” ‹8” £’ —˜‘ ™š¢›œž!ŸŸ  $ž†¡ ¡ž 3Ÿ¤¥ ¦†§ ¨†©8ª «§¬ ¤†­ ®i­ ¯wª °8¥ ±² ¤†³!´!µ ³8¶Second Step• After the group by
  9. 9. SQL9Fall 2001 Database Systems 17Third Step• The SELECT statement creates a single tuple for eachgroup.• The aggregates functions are applied to each groupindividually. ¢¡¤£¦¥¨§© ¦!$# % $!()103254 687 9A@$B C¤@ DE¦F GHG8F I!PRQ S B T UV5WYXG 27!7 C¤@$B T U` F G 6 @$T 9Fall 2001 Database Systems 18GROUP BY HAVING• Find the items with 2 or more bids and with the averagebid greater than $20, for each item list the item nameSELECT I.nameFROM Items I, Bids BWHERE I.Iid = B.IidGROUP BY I.nameHAVING avg(B.Amount) 20 ANDcount(DISTINCT B.Bid) = 2• Find all buyer and item pairs where the buyer placedmore than one bid on the same itemSELECT B.buyid, B.iidFROM Bids BGROUP BY B.buyid, B.iidHAVING count(B.bid) 1
  10. 10. SQL10Fall 2001 Database Systems 19• Find owners who have at least two items withaverage bids greater than $20 for each item. List theowner identifiers and the names of the items.SELECT I2.Oid, I2.NameFROM Items I2WHERE I2.Oid IN (SELECT I.OidFROM Items IWHERE I.Iid IN (SELECT B.IidFROM Bids BGROUP BY B.IidHAVING Avg(Amount) 20)GROUP BY I.Oid HAVING Count(*) = 2)AND I2.Iid IN (SELECT B.IidFROM Bids BGROUP BY B.IidHAVING Avg(Amount) 20)Fall 2001 Database Systems 20ORDER BY• Follows group by and orders the results in ascending ordescending order• Example: Find buyer and item pairs in which the buyer hasmore than one bid for the item, order the result in descendingorder of buyer idsSELECT B.buyid, B.iidFROM Bids BGROUP BY B.buyid, B.iid HAVING count(B.bid) 1ORDER BY B.buyid DESC
  11. 11. SQL11Fall 2001 Database Systems 21SELECT complete• First the Cartesian product of all tables in the from clause is formed• From this, rows not satisfying the where condition are eliminated• The remaining rows are grouped in accordance with the group byclause• Groups not satisfying the having clause then eliminated• The expressions of the select clause target list are evaluated• If the key word distinct is present, duplicate rows are noweliminated• The union is taken after each Subselect is evaluated• Finally, the set of all result rows is sorted if an order by clause ispresent.Fall 2001 Database Systems 22Join types• It is possible to define a join in the from clause– INNER JOIN: regular join from relational algebrawhere only tuples from the two tables satisfying thejoin condition are chosen– LEFT OUTER JOIN: (regular join) union (tuples fromthe table to the left that did not join with any tuples,padded with null values for the new attributes)– RIGHT OUTER JOIN: (regular join) union (tuples fromthe table to the right that did not join with any tuples,padded with null values for the new attributes)– FULL JOIN = LEFT RIGHT OUTER JOIN
  12. 12. SQL12Fall 2001 Database Systems 23Join Examples• Find names of all items with bidsSELECT DISTINCT Items.nameFROM Items INNER JOIN BidsON Items.Iid = Bids.Iid• Find all items and the total number of bids on themSELECT Items.Iid, Count(Bids.Bid)FROM Items LEFT OUTER JOIN BidsON Items.Iid = Bids.IidGROUP BY Items.IidFall 2001 Database Systems 24Left Outer Join Result• The result of the left outer join in the preceding query is: ¢¡¤£ ¥§¦ ¨ © ¢¦ ¨ ¥¢¤¤¨ !$#¤% (¦ ¨ )01!$ 2¤#3¦ #¤%4§5 687 91@¤A1B C§7 48D 7FE G(7 HPIQ1R S¤T 4U¤TVWU1X4§5 6¢D 91@¤A1B C1Y 48E `§E GaA b1UcedfQTfT gQ1R RQ T4§5 6¢A 91@¤A§7 C§7 41Y 7F9 G(7 HPIQ1R S¤T 4U¤TVWU1X4§5 6Y h¢@7 C¢` 48E ipE G(7 q¤5 dS 4U¤TVWU1X4§5 6¢E h¢@7 C§7 48D D1B G(7 HPIQ1R S¤T 4U¤TVWU1X4§5 61` h¢@¤D C1Y 41Y i8B GaA b1UcedfQTfT gQ1R RQ T4§5 6i h¢@¤D C8D 4§7 Y GaD gr5 dd5 Xfst4 urUvfTVWU¢X4§5 6¢9 h¢@¤A C8D 48A E GaD gr5 dd5 Xfst4 urUvfTVWU¢XC8A GaD w§S§R STIUdfS x0S1y€pU‚ƒC8E G0Y q¤5 IQTfTfU HS¤QVVR SResult of itemsinner join bidsThe additionaltuples resulting fromthe left outer join
  13. 13. SQL13Fall 2001 Database Systems 25 ¢¡¤£¦¥¨§¨©   £ ¨ !#¦$% Smith@aol.com¢( )102435 Johns@geocities.com¢6 78902@A3 Brown@netmail.comCB D#89EF Gray@microsoft.comG¨HAIAP1Q¨R G¨SUT1VW X¦Y4`¦a P¨`CY1V bc1d eAfgUh Gray@microsoft,comcpi qpr4stfuUv Robert432@aol.comcpw xyr2€19v Johns@somewhere.comc‚ xygƒvƒr¨ Jj@yahoo.comcp„ …‡†2ˆ‰t Duke@jazz.com2‘C’1“” ¨•– —˜•– ™¦d4eCf g2h‰i‰dj‰•h4kl¨m n˜m oApUq¨rs2t u4v‰tUwUv¨xl4y ny z|{ }2}2{ x~u1{ €ƒ ‚v2ƒUtƒwUv4xl4„ ny …#s1rs2t‰pƒv}ƒs †¦s‡‰ˆ#v2€‰Šl‰‹ n„ Œpv2¢}ƒqUtƒt z#q4r rqUtl4Ž nC‹  ƒvƒ‰€¢‘pv’‰“4”{ pUqƒtUtƒvo#sqUwUwrsl• n˜m { }Us u4v‰tUwUv¨x –#—‡˜C™ –Aš › ˜Cœ12ž —#š › –‡Ÿ y—1› ¡˜¢£1Ÿ4¤4¥|¦ §¨ ©‡ªp«1¬ ­‡¨ ¥|® ¨ƒ¯¥|¦ §|® ©‡ªp«1¬ ­p° ¥|¯ ±|¯¥|¦ §|« ©‡ªp«A¨ ­‡¨ ¥#° ¨U©¥|¦ §#° ²‡ª1¨ ­y± ¥|¯ ³¯¥|¦ §|¯ ²‡ª1¨ ­‡¨ ¥|® ®y¬¥|¦ §A± ²‡ªp® ­p° ¥#° ³‡¬¥|¦ §‡³ ²‡ªp® ­#® ¥¨ °¥|¦ §A© ²‡ªp« ­#® ¥|« ¯Auction DatabaseFall 2001 Database Systems 26Example 1• Find the name and email of owners of items located in“Boston”SELECT O.Name, O.EmailFROM Owners O, Items IWHERE I.Location = ‘Boston’ ANDI.Oid = O.Oid
  14. 14. SQL14Fall 2001 Database Systems 27Example 2• Find the identifiers and amount of bids placed bybuyer “Roberts”SELECT B.Bid, B.AmountFROM Bids B, Buyers BuyWHERE Buy.Name = ‘Roberts’ ANDBuy.Buyid = B.BuyidFall 2001 Database Systems 28Example 3• Find the names of buyers who placed a bid on anitem owned by “Brown”SELECT DISTINCT Buy.NameFROM Bids B, Buyers Buy, Owners O, Items IWHERE O.Name = ‘Brown’ ANDO.Oid = I.Oid ANDI.Iid = B.Iid ANDB.Buyid = Buy.Buyid
  15. 15. SQL15Fall 2001 Database Systems 29Example 4• Find the identifier of items with more than one bidSELECT B.IidFROM Bids BGROUP BY B.Iid HAVING count(B.Bid) 1orSELECT DISTINCT B.IidFROM Bids BWHERE EXISTS (SELECT *FROM Bids B2WHERE B2.Iid = B.Iid AND B2.Bid B.Bid)Fall 2001 Database Systems 30Example 5• Find the names of items all buyers placed a bid onFind the names of items for which there does not exist a buyerwho did not place a bid on this itemSELECT I.nameFROM Items IWHERE NOT EXISTS (SELECT *FROM Buyers BuyWHERE NOT EXISTS (SELECT *FROM Bids BWHERE Buy.Buyid = B.Buyid ANDB.Iid = I.Iid ))
  16. 16. SQL16Fall 2001 Database Systems 31Expressions• Each predicate in the WHERE clause can evaluate to– TRUE– FALSE– UNKNOWN• Example:SELECT B.*FROM Bids BWHERE B.amount (SELECT max(B1.amount)FROM Bids B1, Items IWHERE B1.iid=I.iid ANDI.location = “Boston”)What if there are no tuplesin this expression?Fall 2001 Database Systems 32Unknown expressions• Expressions that compare a value against a possibly nullvalue return the truth value “Unknown” (U).• Logically Unknown is different than True or False.– Not U = U– U and True = U– U and U = U– U and False = False– U or True = True– U or U = U– U or False = U
  17. 17. SQL17Fall 2001 Database Systems 33Unknown Expressions• Unknown valued tuples do not contribute to a query resultSELECT B.*FROM Bids BWHERE B.amount ALL (SELECT B1.amountFROM Bids B1, Items IWHERE B1.iid=I.iid ANDI.location = “Boston”)This query will not return any tuples if the amount forsome bids in Boston is “null”.Fall 2001 Database Systems 34Data Management• Creating tables, inserting and deleting tuples, and updatingcolumn values can be done by SQL statement.CREATE TABLE tablename( colname1 TYPE [NOT NULL],…,PRIMARY KEY(colname1,…))INSERT INTO tablename(colname1,colname2,…)VALUES (…)
  18. 18. SQL18Fall 2001 Database Systems 35More Data Management• Insert can also involve a SELECT conditionINSERT INTO BUYERS(buyid,name, email)SELECT next(buyid), O.name, O.emailFROM Owners OWHERE NOT EXISTS (SELECT * FROM Buyers BWHERE B.name=O.nameAND B.email=O.email)Fall 2001 Database Systems 36Delete• The Delete statement involves a “WHERE” condition thatspecifies the range of tuples that should be deleted from therelation.DELETE FROM BidsWHERE Bids.Iid IN (SELECT I.iid FROM Items IWHERE I.oid = ‘O1’)
  19. 19. SQL19Fall 2001 Database Systems 37Update• The Update statement includes a range condition(WHERE) and a set condition for the new values.• For each tuple t that satisfies the where condition,run the expression in the set statement.UPDATE itemsSET avgbid = (SELECT avg(B.amount)FROM Bids BWHERE B.iid = items.iid)WHERE items.location = ‘Boston’