Home >Documents >Advanced SQL Queries

Advanced SQL Queries

Date post:01-Jan-2016
Category:
View:91 times
Download:6 times
Share this document with a friend
Description:
Advanced SQL Queries. Example Tables Used. Rewriting Minus Queries. Name and id of sailors that has reserved at least one red boat and has never reserved green boat. SELECT S.sname, S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid - PowerPoint PPT Presentation
Transcript:
  • Advanced SQL Queries

  • Example Tables Used

    Reservessidbidday225810110310/10/0411/12/04

    Sailorssidsnameratingage223158DustinLubberRusty781045.055.535.0

    Boatsbidbnamecolor101103NancyGloriaredgreen

  • Rewriting Minus QueriesSELECT S.sname, S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = red MINUS SELECT S.sname, S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = green;Name and id of sailors that has reserved at least one red boat and has never reserved green boat

  • Rewriting Minus Queries Using Not InSELECT S.sname, S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = red and S.sid NOT IN ( SELECT R.sidFROM Boats B, Reserves RWHERE R.bid = B.bid and B.color = green);

  • Rewriting Minus Queries Using Not ExistsSELECT S.sname, S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = red and NOT EXISTS ( SELECT *FROM Boats B, Reserves RWHERE R.sid = S.sid and R.bid = B.bid and B.color = green);

  • DivisionConsider: A(X,Y) and B(Y).

    Then AB =

    In general, we require that the set of fields in B be contained in those of A.

  • Suppliers from A who supply All Parts from B (1)A=

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Suppliers from A who supply All Parts from B (1)A=S1S2S3S4

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Suppliers from A who supply All Parts from B (2)A=

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Suppliers from A who supply All Parts from B (2)A=S1S4

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Suppliers from A who supply All Parts from B (3)A=

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Suppliers from A who supply All Parts from B (3)A=S1

    snopnoS1S1S1S1S2S2S3S4S4P1P2P3P4P1P2P2P2P4

  • Sailors who Reserved all Boats(sid,bid Reserves) (bid Boats)Sailor S whose "set of boats reserved" contains the "set of all boats"

  • Division in SQL (1)SELECT sidFROM Sailors SWHERE NOT EXISTS(SELECT B.bid FROM Boats B WHERE B.bid NOT IN(SELECT R.bid FROM Reserves R WHERE R.sid = S.sid));Sailor S for which there does not exist a boat B in Boats that he did not reserve

  • Division in SQL (2)SELECT S.sid FROM Sailors S WHERE NOT EXISTS(SELECT B.bid FROM Boats B WHERE NOT EXISTS(SELECT R.bid FROM Reserves R WHERE R.bid=B.bid and R.sid=S.sid))Sailor S for which there does not exist a boat B in Boats that he did not reserve

  • Division in SQL (3)SELECT S.sid FROM Sailors S WHERE NOT EXISTS((SELECT B.bid FROM Boats B) MINUS (SELECT R.bid FROM Reserves R WHERE R.sid = S.sid));Sailor S for which there does not exist a boat B in Boats for which there is no reservation in Reserves

  • Aggregation

  • Aggregate OperatorsThe aggregate operators available in SQL are:COUNT(*)COUNT([DISTINCT] A)SUM([DISTINCT] A)AVG([DISTINCT] A)MAX(A)MIN(A)NULL values are ignored

  • Some ExamplesSELECT COUNT(*) FROM Sailors SSELECT AVG(S.age) FROM Sailors S WHERE S.rating=10SELECT COUNT(distinct color) FROM BoatsSELECT COUNT(sid) FROM Sailors S

  • Find Average Age for each RatingSo far, aggregation has been applied to all tuples that passed the WHERE clause test.How can we apply aggregation to groups of tuples?

  • Basic SQL Query SELECT [Distinct] target-list FROM relation-list WHERE conditionGROUP BY grouping-list HAVING group-condition;target-list: Fields appearing in grouping-list and aggregation operatorsgroup-condition: Can only constrain attributes appearing in grouping-list and aggregation operators

  • EvaluationCompute cross product of relations in FROMTuples failing WHERE are thrown awayTuples are partitioned into groups by values of grouping-list attributesThe group-condition is applied to eliminate groupsOne answer in generated for each group

  • Find Average Age for each RatingSELECT AVG(age)FROM SailorsGROUP BY rating;

  • 4055.534

    Sailorssidsnameratingage223158637884DustinLubberRustyFluffyMorleyPopeye7810771045.055.535.044.031.033.0

    Sailorssidsnameratingage226378315884DustinFluffyMorleyLubberRustyPopeye7778101045.044.031.055.535.033.0

  • Find name and age of oldest SailorSELECT S.sname, MAX(S.age) FROM Sailors SWrong!SELECT S.sname, MAX(S.age) FROM Sailors SGROUP BY S.snameWrong: we dont obtain what we want

  • Find name and age of oldest SailorSELECT S.sname, S.age FROM Sailors S WHERE S.age >= ALL (SELECT S2.age FROM Sailors S2)SELECT S.sname, S.age FROM Sailors S WHERE S.age = (SELECT MAX(S2.age) FROM Sailors S2)Right!!How else can this be done?Hint: >= ALL

  • What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=redGROUP BY B.bidTuples: (id of reserved red boat, number of reservations of the red boat)What would happen if we put the condition about the color in the HAVING clause?

  • What would happen if we put the condition about the color in the HAVING clause? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bidGROUP BY B.bid, B.colorHAVING B.color=redWe have also to put the color in the grouping list!

  • Names of Boats that were not Reserved on more than 5 days SELECT bname FROM Boats B, Reserves R WHERE R.bid=B.bid GROUP BY bid, bname HAVING count(DISTINCT day)
  • The Color for which there are the most boats SELECT color FROM Boats BGROUP BY color HAVING max(count(bid))

  • The Color for which there are the most boats SELECT color FROM Boats BGROUP BY color HAVING count(bid) >= ALL(SELECT count(bid)FROM BoatsGROUP BY Color)

  • Aggregation Instead of ExistsAggregation can take the place of exists.Example:SELECT color FROM Boats B1 WHERE NOT EXISTS(SELECT * FROM Boats B2 WHERE B1.bid B2.bid AND B1.color=B2.color)The color of the boat that there is no other boat of this color

  • Aggregation Instead of Exists SELECT color FROM Boats B1GROUP BY color HAVING count(bid) = 1

  • Sub-queries and Views

  • A Complex QueryWe would like to create a table containing 3 columns:Sailor idSailor ageAge of the oldest Sailor

  • Attempt 1SELECT S.sid, S.age, MAX(S.age) FROM Sailors S;

  • Attempt 2 SELECT S.sid, S.age, MAX(S.age) FROM Sailors SGROUP BY S.sid, S.age;

  • Solution 1:Sub-query in FROMSELECT S.sid, S.age, M.mxage FROM Sailors S,(SELECT MAX(S2.age) as mxageFROM Sailors S2) M;We can put a query in the FROM clause instead of a tableThe sub-query in the FROM clause must be renamed with a range variable (M in this case).

  • Solution 2:Sub-query in SELECTSELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2) FROM Sailors S;A sub-query in the SELECT clause must return at most one value for each row returned by the outer query.

  • Another Example of a Sub-query in SELECTSELECT S.sid, S.age, (SELECT MAX(S2.age) FROM Sailors S2 WHERE S2.age
  • Another Example of a Sub-query in FROM??SELECT S.sid, S.age, M.mxage FROM Sailors S, (SELECT MAX(S2.age) as mxage FROM Sailors S2WHERE S2.age
  • Solution 3: Create a TableCREATE TABLE MaxAge asSELECT MAX(S.age) as mxage FROM Sailors S;SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAge M;MUST Rename!Problem: how to update MaxAge table?

  • ViewsA view is a "virtual table" defined using a queryYou can use a view as if it were a table, even though it doesn't contain dataThe view is computed every time that it is referenced

  • Advantages and DisadvantagesAdvantages:no memory used for viewsupdate of table does not require updating viewsgives query processor more choices for optimizingDisadvantages:must be recomputed every time usedif tables that view uses are dropped, view data is lost

  • Solution 4: ViewsA View is a query that looks like a table and can be used as a table.

    CREATE OR REPLACE VIEW MaxAge asSELECT MAX(S.age) as mxage FROM Sailors S;SELECT S.sid, S.age, M.mxage FROM Sailors S, MaxAge M;MUST Rename!

  • Another Example of ViewsCREATE OR REPLACE VIEW MaxAges ASSELECT S1.sid, S2.age AS mxageFROM Sailors S1, Sailors S2WHERE S2.age = (SELECT MAX(S3.age) FROM Sailors S3 WHERE S3.age < S1.age);SELECT S.sid, S.age, M.mxageFROM Sailors S, MaxAges MWHERE S.sid = M.sid;

  • Views For Restricting AccessSuppose that we have a table:Grades(Login, Exercise, Grade)We would like a user to only be able to see his own grades. We create the following view and grant privileges to query the view (not the underlying table)CREATE OR REPLACE VIEW UserGrades asSELECT * FROM Grades WHERE Login = User;The system defines the user name.

of 47/47
1 Advanced SQL Queries Advanced SQL Queries
Embed Size (px)
Recommended