Presentation is loading. Please wait.

Presentation is loading. Please wait.

More on Structured Query Language

Similar presentations


Presentation on theme: "More on Structured Query Language"— Presentation transcript:

1 More on Structured Query Language
Indra Budi

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 2

3 Join Expression Cross join Natural join
Join two tables without any conditions Similar to concept of Cartesian product in set concept SQL syntax: <relation> CROSS JOIN <relation> 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 <relation> NATURAL JOIN <relation> 3

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: <relation> JOIN <relation> ON <condition> 4

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: <relation1> OUTER JOIN <relation2> It is modified by: Optional NATURAL in front of OUTER. Optional ON <condition> after JOIN. 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. 5

6 Example-Cross Join SELECT * FROM Beers CROSS JOIN Likes Likes Beers
name manf Beer 1 XYZ Beer 2 ABC Beer 3 name manf drinker Beer Beer 1 XYZ Andika Panca Mahesa Beer 3 Beer 2 ABC Likes drinker beer Andika Beer 1 Panca Mahesa Beer 3 6

7 Example-Natural Join SELECT * FROM Beers NATURAL JOIN Likes Frequents
drinker beer Andika Beer 1 Mahesa Panca Beer 3 Siti Beer 2 SELECT * FROM Beers NATURAL JOIN Likes drinker beer bar Andika Beer 1 Zanz Panca Beer 3 ABC Frequents drinker bar Tyas ABC Bambang XYZ Panca Andika Zanz 7

8 Example-Theta Join Beers name manf Beer 1 XYZ Beer 2 ABC Beer 3 SELECT * FROM Beers B JOIN Likes L ON B.name = L.beer name manf drinker beer Beer 1 XYZ Aryo Lamo Beer 3 ABC Amir Likes drinker beer Aryo Beer 1 Lamo Amir Beer 3 8

9 Example-Outer Join Likes Beers
SELECT * FROM Beers B LEFT OUTER JOIN Likes L ON B.name = L.beer Beers name manf drinker beer Beer 1 XYZ Aryo Amir Beer 2 ABC Beer 3 Fitria name manf Beer 1 XYZ Beer 2 ABC Beer 3 Likes SELECT * FROM Beers B RIGHT OUTER JOIN Likes L ON B.name = L.beer drinker beer Aryo Beer 1 Amir Siti Beer 3 Fitria Beer 5 name manf drinker beer Beer 1 XYZ Aryo Amir Beer 3 ABC Siti Fitria Beer 5 9

10 Example-Outer Join Likes Beers
name manf Beer 1 XYZ Beer 2 ABC Beer 3 SELECT * FROM Beers B FULL OUTER JOIN Likes L ON B.name = L.beer name manf drinker beer Beer 1 XYZ Aryo Amir Beer 2 ABC Beer 3 Siti Fitria Beer 5 Likes drinker beer Aryo Beer 1 Amir Siti Beer 3 Fitria Beer 5 10

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. 11

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) 12

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’; 13

14 Example Sells SELECT AVG(price) as average_price FROM Sells
WHERE beer = ‘Beer 2’; Sells average_price 7.33 bar beer price ABC Beer 1 5 Beer 2 8 XYZ Beer 3 FGH 7 WXY SELECT AVG(DISTINCT price) as average_price FROM Sells WHERE beer = ‘Beer 2’; average_price 7.5 14

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. 15

16 Example: Effect of NULL’s
SELECT count(*) FROM Sells WHERE beer = ‘Bud’; The number of bars that sell Bud. bar beer price ABC Beer 1 5 Bud 8 XYZ Beer 3 FGH 7 WXY The result : 3 SELECT count(price) FROM Sells WHERE beer = ‘Bud’; The number of bars that sell Bud at a known price (price not NULL) The result : 2 16

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. 17

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) 18

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. 19

20 Restriction on SELECT Lists With Aggregation
If any aggregation is used, then each element of the SELECT list must be either: Aggregated, or An attribute on the GROUP BY list. 20

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. 21

22 HAVING Clauses HAVING vs WHERE
HAVING  filtering group WHERE  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. 22

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: A grouping attribute, or Aggregated. 23

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 24

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. 25

26 Solution SELECT beer, AVG(price) FROM Sells GROUP BY beer
Beer groups with at least 3 non-NULL bars and also beer groups where the manufacturer is Pete’s. 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. 26

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: Insert a tuple or tuples. Delete a tuple or tuples. Update the value(s) of an existing tuple or tuples. 27

28 Insertion 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’); 28

29 Specifying Attributes in INSERT
We may add to the relation name a list of attributes. There are two reasons to do so: We forget the standard order of attributes for the relation. We don’t have values for all attributes, and we want the system to fill in missing components with NULL or a default value. 29

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’); 30

31 Inserting Many Tuples We may insert the entire result of a query into a relation, using the form: INSERT INTO <relation> ( <subquery> ); 31

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. 32

33 Solution INSERT INTO PotBuddies (SELECT d2.drinker
The other drinker Pairs of Drinker tuples where the first is for Sally, the second is for someone else, and the bars are the same. INSERT INTO PotBuddies (SELECT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = ‘Sally’ AND d2.drinker <> ‘Sally’ AND d1.bar = d2.bar ); 33

34 Deletion To delete tuples satisfying a condition from some relation:
DELETE FROM <relation> WHERE <condition>; 34

35 Example: Deletion Delete from Likes(drinker, beer) the fact that Sally likes Bud: DELETE FROM Likes WHERE drinker = ‘Sally’ AND beer = ‘Bud’; 35

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 ? 36

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. 37

38 Updates To change certain attributes in certain tuples of a relation:
UPDATE <relation> SET <list of attribute assignments> WHERE <condition on tuples>; 38

39 Example: Update Change drinker Fred’s phone number to 555-1212:
UPDATE Drinkers SET phone = ‘ ’ WHERE name = ‘Fred’; 39

40 Example: Update Several Tuples
Make $4 the maximum price for beer: UPDATE Sells SET price = 4.00 WHERE price > 4.00; 40

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” 41

42 SQL View Definition Features of Views Reasons for 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#; 42

43 View Definition in Ongoing Example
First View: Attribute Names are Inherited CREATE VIEW WORKS_ON1 AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER ; Second View: View attribute names are Aliased via a one-to-one Correspondence with the SELECT-clause CREATE 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 ; 43

44 Queries on Views Retrieve the Last Name and First Name of All Employees Who Work on 'ProjectX'. SELECT PNAME, FNAME, LNAME FROM WORKS_ON1 WHERE PNAME='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 44

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#; If we want to change the total quantity SUMQTY of a part P1 in PQ from “30” to “40”, a view update problem incurs, because this update over view PQ does not give enough information to enable us to map the view update to the base relations without ambiguity. 45


Download ppt "More on Structured Query Language"

Similar presentations


Ads by Google