more on structured query language indra budi [email protected]
TRANSCRIPT
More onStructured Query Language
Indra [email protected]
2 Fakultas Ilmu Komputer UI
Join ExpressionJoin Expression
Permitting user to specify a table resulting from join operation in FROM clause of a queryTypes of join:
Cross join (cross product)Natural joinTheta joinOuter join
3 Fakultas Ilmu Komputer UI
Join ExpressionJoin Expression
Cross joinJoin two tables without any conditionsSimilar to concept of Cartesian product in set conceptSQL syntax:
<relation> CROSS JOIN <relation>
Natural joinRequiring the two join attributes have the same attribute namesChange the attribute name if the attributes have different nameThe resulting relation contains all attributes from the two tables, but only one join attribute is keptSQL syntax:
<relation> NATURAL JOIN <relation>
4 Fakultas Ilmu Komputer UI
Join ExpressionJoin Expression
Theta joinJoining two related tables using join condition in FROM clauseThe resulting relation contains all attributes from the two tables, including the attribute(s) for join conditionSQL Syntax:
<relation> JOIN <relation> ON <condition>
5 Fakultas Ilmu Komputer UI
Join ExpressionJoin ExpressionOuter 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 joinSQL Syntax:
<relation1> OUTER JOIN <relation2> It is modified by:
1.Optional NATURAL in front of OUTER.2.Optional ON <condition> after JOIN.3.Optional LEFT, RIGHT, or FULL before OUTER.
LEFT = pad dangling tuples of relation1 only.
RIGHT = pad dangling tuples of relation2 only.
FULL = pad both; this choice is the default.
6 Fakultas Ilmu Komputer UI
Example-Cross JoinExample-Cross Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
drinker
beer
Andika Beer 1
Panca Beer 1
Mahesa
Beer 3
SELECT * FROM Beers CROSS JOIN Likes
name manf drinker Beer
Beer 1 XYZ Andika Beer 1
Beer 1 XYZ Panca Beer 1
Beer 1 XYZ Mahesa Beer 3
Beer 2 ABC Andika Beer 1
Beer 2 ABC Panca Beer 1
Beer 2 ABC Mahesa Beer 3
Beer 3 ABC Andika Beer 1
Beer 3 ABC Panca Beer 1
Beer 3 ABC Mahesa Beer 3
7 Fakultas Ilmu Komputer UI
Example-Natural JoinExample-Natural JoinLikes
drinker
beer
Andika Beer 1
Mahesa
Beer 1
Panca Beer 3
Siti Beer 2
Frequents
drinker bar
Tyas ABC
Bambang XYZ
Panca ABC
Andika Zanz
SELECT * FROM Beers NATURAL JOIN Likes
drinker beer bar
Andika Beer 1 Zanz
Panca Beer 3 ABC
8 Fakultas Ilmu Komputer UI
Example-Theta JoinExample-Theta Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
drinker
beer
Aryo Beer 1
Lamo Beer 1
Amir Beer 3
SELECT * FROM Beers B JOIN Likes L ON B.name = L.beer
name manf drinker beer
Beer 1 XYZ Aryo Beer 1
Beer 1 XYZ Lamo Beer 1
Beer 3 ABC Amir Beer 3
9 Fakultas Ilmu Komputer UI
Example-Outer JoinExample-Outer Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
SELECT * FROM Beers B LEFT OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Aryo Beer 1
Beer 1 XYZ Amir Beer 1
Beer 2 ABC
Beer 3 ABC Fitria Beer 3
drinker
beer
Aryo Beer 1
Amir Beer 1
Siti Beer 3
Fitria Beer 5
SELECT * FROM Beers B RIGHT OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Aryo Beer 1
Beer 1 XYZ Amir Beer 1
Beer 3 ABC Siti Beer 3
Fitria Beer 5
10 Fakultas Ilmu Komputer UI
Example-Outer JoinExample-Outer Join
Beers
name manf
Beer 1 XYZ
Beer 2 ABC
Beer 3 ABC
Likes
SELECT * FROM Beers B FULL OUTER JOIN Likes L ON B.name = L.beername manf drinker beer
Beer 1 XYZ Aryo Beer 1
Beer 1 XYZ Amir Beer 1
Beer 2 ABC
Beer 3 ABC Siti Beer 3
Fitria Beer 5
drinker
beer
Aryo Beer 1
Amir Beer 1
Siti Beer 3
Fitria Beer 5
11 Fakultas Ilmu Komputer UI
AggregationsAggregations
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.
12 Fakultas Ilmu Komputer UI
Example: AggregationExample: Aggregation
From Sells(bar, beer, price), find the average price of Bud:
SELECT AVG(price)FROM SellsWHERE beer = ‘Bud’;
From Sells(bar, beer, price), find the cheapest and the most expensive price of Bud:
SELECT MIN(price), MAX(price)FROM SellsWHERE beer = ‘Bud’;
13 Fakultas Ilmu Komputer UI
Eliminating Duplicates in an AggregationEliminating 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’;
14 Fakultas Ilmu Komputer UI
ExampleExample
Sells
bar beer price
ABC Beer 1 5
ABC Beer 2 8
XYZ Beer 3 5
FGH Beer 2 7
WXY Beer 2 7
SELECT AVG(price) as average_priceFROM SellsWHERE beer = ‘Beer 2’;
average_price
7.33
SELECT AVG(DISTINCT price) as average_priceFROM SellsWHERE beer = ‘Beer 2’;
average_price
7.5
15 Fakultas Ilmu Komputer UI
NULL’s Ignored in AggregationNULL’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.
16 Fakultas Ilmu Komputer UI
Example: Effect of NULL’sExample: Effect of NULL’s
SELECT count(*)FROM SellsWHERE beer = ‘Bud’;
The number of barsthat sell Bud.
SELECT count(price)FROM SellsWHERE beer = ‘Bud’;
The number of barsthat sell Bud at aknown price (price not NULL)
bar beer price
ABC Beer 1 5
ABC Bud 8
XYZ Beer 3 5
FGH Bud 7
WXY Bud
The result : 3
The result : 2
17 Fakultas Ilmu Komputer UI
GroupingGrouping
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.
18 Fakultas Ilmu Komputer UI
Example: GroupingExample: 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;
19 Fakultas Ilmu Komputer UI
Example: GroupingExample: 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, SellsWHERE beer = ‘Bud’ AND
Frequents.bar = Sells.barGROUP BY drinker;
Computedrinker-bar-price of Budtuples first,then groupby drinker.
20 Fakultas Ilmu Komputer UI
Restriction on SELECT Lists With AggregationRestriction on SELECT Lists With Aggregation
If any aggregation is used, then each element of the SELECT list must be either:
1. Aggregated, or2. An attribute on the GROUP BY list.
21 Fakultas Ilmu Komputer UI
Illegal Query ExampleIllegal Query Example
You might think you could find the bar that sells Bud the cheapest by:
SELECT bar, MIN(price)FROM SellsWHERE beer = ‘Bud’;
But this query is illegal in SQL.Why? Note bar is neither aggregated nor on the GROUP BY list.
22 Fakultas Ilmu Komputer UI
HAVING ClausesHAVING Clauses
HAVING vs WHEREHAVING filtering groupWHERE filtering tuples
HAVING <condition> may follow a GROUP BY clause.If so, the condition applies to each group, and groups not satisfying the condition are eliminated.
23 Fakultas Ilmu Komputer UI
Requirements on HAVING ConditionsRequirements 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, or2. Aggregated.
24 Fakultas Ilmu Komputer UI
Example: HAVINGExample: 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 SellsGROUP BY beerHAVING MIN(price) >= 4 AND MIN(price) <=10
25 Fakultas Ilmu Komputer UI
Example: HAVINGExample: 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.
26 Fakultas Ilmu Komputer UI
SolutionSolution
SELECT beer, AVG(price)FROM SellsGROUP BY beerHAVING COUNT(bar) >= 3 OR
beer IN (SELECT name FROM Beers WHERE manf = ‘Pete’’s’);
Beers manu-factured byPete’s.
Beer groups with at least3 non-NULL bars and alsobeer groups where themanufacturer is Pete’s.
27 Fakultas Ilmu Komputer UI
Database ModificationsDatabase 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.
28 Fakultas Ilmu Komputer UI
InsertionInsertion
To insert a single tuple:INSERT INTO <relation>VALUES ( <list of values> );
Example: add to Likes(drinker, beer) the fact that Sally likes Bud.
INSERT INTO Likes
VALUES(‘Sally’, ‘Bud’);
29 Fakultas Ilmu Komputer UI
Specifying Attributes in INSERTSpecifying 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.
30 Fakultas Ilmu Komputer UI
Example: Specifying AttributesExample: Specifying Attributes
Another way to add the fact that Sally likes Bud to Likes(drinker, beer):
INSERT INTO Likes(beer, drinker)
VALUES(‘Bud’, ‘Sally’);
31 Fakultas Ilmu Komputer UI
Inserting Many TuplesInserting Many Tuples
We may insert the entire result of a query into a relation, using the form:
INSERT INTO <relation>( <subquery> );
32 Fakultas Ilmu Komputer UI
Example: Insert a SubqueryExample: 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.
33 Fakultas Ilmu Komputer UI
SolutionSolution
INSERT INTO PotBuddies(SELECT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = ‘Sally’ AND
d2.drinker <> ‘Sally’ ANDd1.bar = d2.bar
);
Pairs of Drinkertuples where thefirst is for Sally,the second is forsomeone else,and the bars arethe same.
The otherdrinker
34 Fakultas Ilmu Komputer UI
DeletionDeletion
To delete tuples satisfying a condition from some relation:
DELETE FROM <relation>WHERE <condition>;
35 Fakultas Ilmu Komputer UI
Example: DeletionExample: Deletion
Delete from Likes(drinker, beer) the fact that Sally likes Bud:
DELETE FROM Likes
WHERE drinker = ‘Sally’ AND
beer = ‘Bud’;
36 Fakultas Ilmu Komputer UI
Example: Delete all TuplesExample: 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 ?
37 Fakultas Ilmu Komputer UI
Example: Delete Many TuplesExample: Delete Many Tuples
Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer.
DELETE FROM Beers bWHERE EXISTS (
SELECT name FROM BeersWHERE manf = b.manf AND
name <> b.name);
Beers with the samemanufacturer anda different namefrom the name ofthe beer representedby tuple b.
38 Fakultas Ilmu Komputer UI
UpdatesUpdates
To change certain attributes in certain tuples of a relation:
UPDATE <relation>SET <list of attribute assignments>WHERE <condition on tuples>;
39 Fakultas Ilmu Komputer UI
Example: UpdateExample: Update
Change drinker Fred’s phone number to 555-1212:
UPDATE Drinkers
SET phone = ‘555-1212’
WHERE name = ‘Fred’;
40 Fakultas Ilmu Komputer UI
Example: Update Several TuplesExample: Update Several Tuples
Make $4 the maximum price for beer:UPDATE Sells
SET price = 4.00
WHERE price > 4.00;
41 Fakultas Ilmu Komputer UI
SQL Support for ViewsSQL Support for Views
Views are Part of the SQL DDLAbstracting from Conceptual to External Schema
View Hides the DetailsOne or More Tables in Conceptual Schema May be Combined (in Part) to Form a ViewDon’t Include FKs and Other Internal AttributesTypically, 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”
42 Fakultas Ilmu Komputer UI
Features of ViewsView Represents a Restricted Portion (Rows, Columns) of a Relation - External Schema in SQLView is Virtual Table View (Not Stored) and Must be Re-evaluated Every Time - DynamicLike Relation, a View Can Be Deleted at Any TimeAttributes Can Be Renamed in View
Reasons for ViewsSecurity Increasing Application-Data Independence
CREATE VIEW PQ(P#, SUMQTY) AS SELECT P#, SUM(QTY) FROM SP GROUP BY P#;
SQL View DefinitionSQL View Definition
43 Fakultas Ilmu Komputer UI
First View: Attribute Names are InheritedCREATE VIEW WORKS_ON1 ASSELECT FNAME, LNAME, PNAME, HOURSFROM EMPLOYEE, PROJECT, WORKS_ONWHERE SSN=ESSN AND PNO=PNUMBER ;
Second View: View attribute names are Aliased via a one-to-one Correspondence with the SELECT-clauseCREATE VIEW DEPT_INFO(DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) AS SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME ;
View Definition in Ongoing ExampleView Definition in Ongoing Example
44 Fakultas Ilmu Komputer UI
Queries on ViewsQueries on Views
Retrieve the Last Name and First Name of All Employees Who Work on 'ProjectX'.SELECT PNAME, FNAME, LNAMEFROM WORKS_ON1WHEREPNAME='ProjectX' ;
Without the View WORKS_ON1, this Query Specification Would Require Two Join ConditionsA View Can Be Defined to Simplify Frequently Occurring QueriesDBMS Keeps the View Up-to-date if the Base Tables on Which the View is Defined are ModifiedHence, the View is Realized at the Time we Specify a Query on the View
45 Fakultas Ilmu Komputer UI
What is View Update Problem?What is View Update Problem?
Retrieval over View Mirrors a Retrieval over RelationHowever, Update over View may cause Problems!In general, a View Update may Introduce Ambiguity when there is more than one way to Update Underlying RelationsConsider 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#;