Presentation on theme: "More on Structured Query Language Indra Budi"— Presentation transcript:
More on Structured Query Language Indra Budi
Fakultas Ilmu Komputer UI 2 Join Expression Permitting user to specify a table resulting from join operation in FROM clause of a query Types of join: Cross join (cross product) Natural join Theta join Outer join
Fakultas Ilmu Komputer UI 3 Join Expression Cross join Join two tables without any conditions Similar to concept of Cartesian product in set concept SQL syntax: CROSS JOIN Natural join Requiring the two join attributes have the same attribute names Change the attribute name if the attributes have different name The resulting relation contains all attributes from the two tables, but only one join attribute is kept SQL syntax: NATURAL JOIN
Fakultas Ilmu Komputer UI 4 Join Expression Theta join Joining two related tables using join condition in FROM clause The resulting relation contains all attributes from the two tables, including the attribute(s) for join condition SQL Syntax: JOIN ON
Fakultas Ilmu Komputer UI 5 Join Expression Outer join Similar to theta join, the difference: Theta join only returns the tuples with a matching tuple (relation) Outer join returns all tuples with or without matching tuple (relation) Types: Left, right and full outer join SQL Syntax: OUTER JOIN It is modified by: 1.Optional NATURAL in front of OUTER. 2.Optional ON after JOIN. 3.Optional LEFT, RIGHT, or FULL before OUTER. uLEFT = pad dangling tuples of relation1 only. uRIGHT = pad dangling tuples of relation2 only. uFULL = pad both; this choice is the default.
Fakultas Ilmu Komputer UI 7 Example-Natural Join Likes drinkerbeer AndikaBeer 1 MahesaBeer 1 PancaBeer 3 SitiBeer 2 Frequents drinkerbar TyasABC BambangXYZ PancaABC AndikaZanz SELECT * FROM Beers NATURAL JOIN Likes drinkerbeerbar AndikaBeer 1Zanz PancaBeer 3ABC
Fakultas Ilmu Komputer UI 8 Example-Theta Join Beers namemanf Beer 1XYZ Beer 2ABC Beer 3ABC Likes drinkerbeer AryoBeer 1 LamoBeer 1 AmirBeer 3 SELECT * FROM Beers B JOIN Likes L ON B.name = L.beer namemanfdrinkerbeer Beer 1XYZAryoBeer 1 XYZLamoBeer 1 Beer 3ABCAmirBeer 3
Fakultas Ilmu Komputer UI 9 Example-Outer Join Beers namemanf Beer 1XYZ Beer 2ABC Beer 3ABC Likes SELECT * FROM Beers B LEFT OUTER JOIN Likes L ON B.name = L.beer namemanfdrinkerbeer Beer 1XYZAryoBeer 1 XYZAmirBeer 1 Beer 2ABC Beer 3ABCFitriaBeer 3 drinkerbeer AryoBeer 1 AmirBeer 1 SitiBeer 3 FitriaBeer 5 SELECT * FROM Beers B RIGHT OUTER JOIN Likes L ON B.name = L.beer namemanfdrinkerbeer Beer 1XYZ Aryo Beer 1 XYZ Amir Beer 1 Beer 3ABC Siti Beer 3 Fitria Beer 5
Fakultas Ilmu Komputer UI 10 Example-Outer Join Beers namemanf Beer 1XYZ Beer 2ABC Beer 3ABC Likes SELECT * FROM Beers B FULL OUTER JOIN Likes L ON B.name = L.beer namemanfdrinkerbeer Beer 1XYZAryoBeer 1 XYZAmirBeer 1 Beer 2ABC Beer 3ABCSitiBeer 3 FitriaBeer 5 drinkerbeer AryoBeer 1 AmirBeer 1 SitiBeer 3 FitriaBeer 5
Fakultas Ilmu Komputer UI 11 Aggregations SUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. Also, COUNT(*) counts the number of tuples.
Fakultas Ilmu Komputer UI 12 Example: Aggregation From Sells(bar, beer, price), find the average price of Bud: SELECT AVG(price) FROM Sells WHERE beer = ‘Bud’; From Sells(bar, beer, price), find the cheapest and the most expensive price of Bud: SELECT MIN(price), MAX(price) FROM Sells WHERE beer = ‘Bud’;
Fakultas Ilmu Komputer UI 13 Eliminating Duplicates in an Aggregation DISTINCT inside an aggregation causes duplicates to be eliminated before the aggregation. Example: find the number of different prices charged for Bud: SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = ‘Bud’;
Fakultas Ilmu Komputer UI 14 Example Sells barbeerprice ABCBeer 15 ABCBeer 28 XYZBeer 35 FGHBeer 27 WXYBeer 27 SELECT AVG(price) as average_price FROM Sells WHERE beer = ‘Beer 2’; average_price 7.33 SELECT AVG(DISTINCT price) as average_price FROM Sells WHERE beer = ‘Beer 2’; average_price 7.5
Fakultas Ilmu Komputer UI 15 NULL’s Ignored in Aggregation NULL never contributes to a sum, average, or count, and can never be the minimum or maximum of a column. But if there are no non-NULL values in a column (all values are NULL), then the result of the aggregation is NULL.
Fakultas Ilmu Komputer UI 16 Example: Effect of NULL’s SELECT count(*) FROM Sells WHERE beer = ‘Bud’; The number of bars that sell Bud. SELECT count(price) FROM Sells WHERE beer = ‘Bud’; The number of bars that sell Bud at a known price (price not NULL) barbeerprice ABCBeer 15 ABCBud8 XYZBeer 35 FGHBud7 WXYBud The result : 3 The result : 2
Fakultas Ilmu Komputer UI 17 Grouping We may follow a SELECT-FROM-WHERE expression by GROUP BY and a list of attributes. The relation that results from the SELECT- FROM-WHERE is grouped according to the values of all those attributes, and any aggregation is applied only within each group.
Fakultas Ilmu Komputer UI 18 Example: Grouping From Sells(bar, beer, price), find the average price for each beer: SELECT beer, AVG(price) FROM Sells GROUP BY beer; From Sells(bar, beer, price), find the cheapest price for each beer: SELECT beer, MIN(price) FROM Sells GROUP BY beer;
Fakultas Ilmu Komputer UI 19 Example: Grouping From Sells(bar, beer, price) and Frequents(drinker, bar), find for each drinker the average price of Bud at the bars they frequent: SELECT drinker, AVG(price) FROM Frequents, Sells WHERE beer = ‘Bud’ AND Frequents.bar = Sells.bar GROUP BY drinker; Compute drinker-bar- price of Bud tuples first, then group by drinker.
Fakultas Ilmu Komputer UI 20 Restriction on SELECT Lists With Aggregation If any aggregation is used, then each element of the SELECT list must be either: 1. Aggregated, or 2. An attribute on the GROUP BY list.
Fakultas Ilmu Komputer UI 21 Illegal Query Example You might think you could find the bar that sells Bud the cheapest by: SELECT bar, MIN(price) FROM Sells WHERE beer = ‘Bud’; But this query is illegal in SQL. Why? Note bar is neither aggregated nor on the GROUP BY list.
Fakultas Ilmu Komputer UI 22 HAVING Clauses HAVING vs WHERE HAVING filtering group WHERE filtering tuples HAVING may follow a GROUP BY clause. If so, the condition applies to each group, and groups not satisfying the condition are eliminated.
Fakultas Ilmu Komputer UI 23 Requirements on HAVING Conditions These conditions may refer to any relation or tuple-variable in the FROM clause. They may refer to attributes of those relations, as long as the attribute makes sense within a group; i.e., it is either: 1.A grouping attribute, or 2.Aggregated.
Fakultas Ilmu Komputer UI 24 Example: HAVING From Sells(bar, beer, price), find the beer name and cheapest price for that beer ranging from 4 to 10. SELECT beer, MIN(price) FROM Sells GROUP BY beer HAVING MIN(price) >= 4 AND MIN(price) <=10
Fakultas Ilmu Komputer UI 25 Example: HAVING From Sells(bar, beer, price) and Beers(name, manf), find the average price of those beers that are either served in at least three bars or are manufactured by Pete’s.
Fakultas Ilmu Komputer UI 26 Solution SELECT beer, AVG(price) FROM Sells GROUP BY beer HAVING COUNT(bar) >= 3 OR beer IN (SELECT name FROM Beers WHERE manf = ‘Pete’’s’); Beers manu- factured by Pete’s. Beer groups with at least 3 non-NULL bars and also beer groups where the manufacturer is Pete’s.
Fakultas Ilmu Komputer UI 27 Database Modifications A modification command does not return a result as a query does, but it changes the database in some way. There are three kinds of modifications: 1. Insert a tuple or tuples. 2. Delete a tuple or tuples. 3. Update the value(s) of an existing tuple or tuples.
Fakultas Ilmu Komputer UI 28 Insertion To insert a single tuple: INSERT INTO VALUES ( ); Example: add to Likes(drinker, beer) the fact that Sally likes Bud. INSERT INTO Likes VALUES(‘Sally’, ‘Bud’);
Fakultas Ilmu Komputer UI 29 Specifying Attributes in INSERT We may add to the relation name a list of attributes. There are two reasons to do so: 1. We forget the standard order of attributes for the relation. 2. We don’t have values for all attributes, and we want the system to fill in missing components with NULL or a default value.
Fakultas Ilmu Komputer UI 30 Example: Specifying Attributes Another way to add the fact that Sally likes Bud to Likes(drinker, beer): INSERT INTO Likes(beer, drinker) VALUES(‘Bud’, ‘Sally’);
Fakultas Ilmu Komputer UI 31 Inserting Many Tuples We may insert the entire result of a query into a relation, using the form: INSERT INTO ( );
Fakultas Ilmu Komputer UI 32 Example: Insert a Subquery Using Frequents(drinker, bar), enter into the new relation PotBuddies(name) all of Sally’s “potential buddies,” i.e., those drinkers who frequent at least one bar that Sally also frequents.
Fakultas Ilmu Komputer UI 33 Solution INSERT INTO PotBuddies (SELECT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = ‘Sally’ AND d2.drinker <> ‘Sally’ AND d1.bar = d2.bar ); Pairs of Drinker tuples where the first is for Sally, the second is for someone else, and the bars are the same. The other drinker
Fakultas Ilmu Komputer UI 34 Deletion To delete tuples satisfying a condition from some relation: DELETE FROM WHERE ;
Fakultas Ilmu Komputer UI 35 Example: Deletion Delete from Likes(drinker, beer) the fact that Sally likes Bud: DELETE FROM Likes WHERE drinker = ‘Sally’ AND beer = ‘Bud’;
Fakultas Ilmu Komputer UI 36 Example: Delete all Tuples Make the relation Likes empty: DELETE FROM Likes; Note no WHERE clause needed. Do this command delete the Likes table from database ?
Fakultas Ilmu Komputer UI 37 Example: Delete Many Tuples Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer. DELETE FROM Beers b WHERE EXISTS ( SELECT name FROM Beers WHERE manf = b.manf AND name <> b.name); Beers with the same manufacturer and a different name from the name of the beer represented by tuple b.
Fakultas Ilmu Komputer UI 38 Updates To change certain attributes in certain tuples of a relation: UPDATE SET WHERE ;
Fakultas Ilmu Komputer UI 39 Example: Update Change drinker Fred’s phone number to : UPDATE Drinkers SET phone = ‘ ’ WHERE name = ‘Fred’;
Fakultas Ilmu Komputer UI 40 Example: Update Several Tuples Make $4 the maximum price for beer: UPDATE Sells SET price = 4.00 WHERE price > 4.00;
Fakultas Ilmu Komputer UI 41 SQL Support for Views Views are Part of the SQL DDL Abstracting from Conceptual to External Schema View Hides the Details One or More Tables in Conceptual Schema May be Combined (in Part) to Form a View Don’t Include FKs and Other Internal Attributes Typically, View is Formed by Join of Two or More Relations Utilizing FKs, PKs, etc. As a Result - View is Independent Once Formed - View Static/Unchangeable to Insulate User Applications from Conceptual Schema Similar in Concept/Intent to “Public Interface”
Fakultas Ilmu Komputer UI 42 Features of Views View Represents a Restricted Portion (Rows, Columns) of a Relation - External Schema in SQL View is Virtual Table View (Not Stored) and Must be Re-evaluated Every Time - Dynamic Like Relation, a View Can Be Deleted at Any Time Attributes Can Be Renamed in View Reasons for Views Security Increasing Application-Data Independence CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#; SQL View Definition
Fakultas Ilmu Komputer UI 43 First View: Attribute Names are Inherited CREATE VIEW WORKS_ON1 AS SELECT FNAME, LNAME, PNAME, HOURS FROMEMPLOYEE, PROJECT, WORKS_ON WHERESSN=ESSN AND PNO=PNUMBER ; Second View: View attribute names are Aliased via a one-to-one Correspondence with the SELECT-clause CREATE VIEWDEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) AS SELECTDNAME, COUNT (*), SUM (SALARY) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER=DNO GROUP BY DNAME ; View Definition in Ongoing Example
Fakultas Ilmu Komputer UI 44 Queries on Views Retrieve the Last Name and First Name of All Employees Who Work on 'ProjectX'. SELECTPNAME, FNAME, LNAME FROMWORKS_ON1 WHEREPNAME='ProjectX' ; Without the View WORKS_ON1, this Query Specification Would Require Two Join Conditions A View Can Be Defined to Simplify Frequently Occurring Queries DBMS Keeps the View Up-to-date if the Base Tables on Which the View is Defined are Modified Hence, the View is Realized at the Time we Specify a Query on the View
Fakultas Ilmu Komputer UI 45 What is View Update Problem? Retrieval over View Mirrors a Retrieval over Relation However, Update over View may cause Problems! In general, a View Update may Introduce Ambiguity when there is more than one way to Update Underlying Relations Consider the view PQ Created Below: Try to Change the Total Quantity SUMQTY of P1 in PQ from “30” to “40” Why Does a view Update Problem occur? CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#;