Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.

Similar presentations


Presentation on theme: "Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi."— Presentation transcript:

1 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi

2 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 2  Define terms  Write single and multiple table SQL queries  Note in SQL Handout 3  Define and use three types of joins  Self-Join  Write noncorrelated and correlated subqueries  Establish referential integrity in SQL

3 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  After the first two tables are joined, the result set is joined to the next table, and so on WHERE/ WHERE/ GROUP HAVING ORDER BY JOIN1 JOIN2 BY 3 T1 R5 R3 R2 R1 T3 T2 R4

4 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Exclude the designated records  Example: Find instructors who do not have the same last name as students SELECT instructor_name Name FROM instructor MINUS SELECT student_lname Name From student 4

5 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 5 Self-joins are often used on tables with unary relationships Note which one is which one! 5 The same table is used on both sides of the join (remember the ERD? – and think about tables); distinguished using table aliases

6 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 6

7 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 7  Subquery–placing an inner query (SELECT statement) inside an outer query  Options: 1. As a “table” of the FROM clause  In this case a view is created in the subquery and the view is then used in the main query 2. In a condition of the WHERE clause 3. Within the HAVING clause  Subqueries can be:  Noncorrelated–executed once for the entire outer query  Correlated–executed once for each row returned by the outer query

8 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 8  What are the name and address of the customer who placed order #1008?  SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS FROM CUSTOMER_T WHERE CUSTOMER_T.CUSTOMER_ID = (SELECT CUSTOMER_ID FROM ORDER_T WHERE ORDER_ID = 1008);  Note : the value for ORDER_ID does NOT appear in the query result; it is used as the selection criterion in the inner query  Data from a subquery cannot be included in the final results  They are only used as ______

9 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Some queries could be accomplished by either a join or a subquery [Examine the query on last slide] 9 Join version Subquery version

10 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 10

11 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 11

12 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 12  Show all customers who have placed an order SELECT CUSTOMER_NAME FROM CUSTOMER_T WHERE CUSTOMER_ID IN (SELECT DISTINCT CUSTOMER_ID FROM ORDER_T); Subquery is embedded in parentheses. In this case it returns a list that will be used in the WHERE clause of the outer query The IN operator will test to see if the CUSTOMER_ID value of a row is included in the list returned from the subquery NOT/ANY/ALL may be used in front of IN; logical operators =, can be used

13 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 13

14 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 14  Show all products whose standard price is higher than the average price The WHERE clause normally cannot include aggregate functions, but because the aggregate is performed in the subquery its result can be used in the outer query’s WHERE clause One column of the subquery is an aggregate function that has an alias name. That alias can then be referred to in the outer query Subquery forms the derived table [view] used in the FROM clause of the outer query Differentiate: column name (header) vs variable

15 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 15  Noncorrelated subqueries:  Do not depend on data from the outer query  Execute once for the entire outer query  i.e. the subquery “first runs by itself”, “then pass the result to outer query”  Correlated subqueries:  Make use of data from the outer query  Execute once for each row of the outer query  Can use the EXISTS operator

16 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 16  EXISTS  take a value of true if the subquery returns an intermediate results table that contains one or more rows (a nonempty set),  false if no rows are returned (empty set)  Query: What are the order IDs for all orders that have included furniture finished in natural ash? SELECT DISTINCT ORDER_ID FROM ORDER_LINE_T WHERE EXISTS (SELECT * FROM PRODUCT_T WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID AND PRODUCT_FINISH = ‘Natural Ash’); Note “select *”…

17 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 17 Figure 7-8a Processing a noncorrelated subquery A noncorrelated subquery processes completely before the outer query begins

18 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 18  Show all orders that include furniture finished in natural ash SELECT DISTINCT OrderID FROM OrderLine_T WHERE EXISTS ( SELECT * FROM Product_T WHERE ProductID = OrderLine_T.ProductID AND Productfinish = ‘Natural ash’ ) ; The subquery is testing for a value that comes from the outer query The EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise it returns a FALSE  A correlated subquery always refers to an attribute from a table referenced in the outer query  passing arguments from outter query

19 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 19 Figure 7-8b Processing a correlated subquery Subquery refers to outer- query data, so executes once for each row of outer query Note: Only the orders that involve products with Natural Ash will be included in the final results. 19 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall

20 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall Evaluate once and result is compared w EACH row of the parent query. SELECT field_list FROM table_list (w possible joins) WHERE field {=,,IN} (Subquery)  With GROUP BY: SELECT field_list FROM table_list (w possible joins) GROUP BY field_list HAVING field {=,,IN} (Subquery) 20 Will the subquery results be displayed?

21 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall Typical scenarios: 1. Rows/Groups with a field value > average of {whole table; a specific group} 2. Groups having a field value >= AVG/COUNT… of{whole table; a specific group} 3. Rows/groups whose certain field value is among a list of valid values (use IN)  Note: in most cases (especially bullet #3), the values from the right-hand-side of the Boolean operators are NOT from the same table of the parent/main query – “reach different table thru SubQ” 21

22 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SELECT field_list FROM (Subquery) WHERE …  Example: display the names and home city of franchisees who currently owns restaurants in California  Example: display the names and home city of franchisees who currently owns restaurants in California, whose credit rating is A or AA 22 Will the subquery results be displayed?

23 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SELECT field_list, (Subquery) FROM table_list WHERE …  Example: 23 Will the subquery results be displayed?

24 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall Pass argument from the main Q INTO subQ Special case: WHERE EXIST… i.e.: “*if* there’s a corresponding row”  Examples: 24 Will the subquery results be displayed ?

25 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 25  Combine the output (union of multiple queries) together into a single result table First query Second query Combine

26 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 26 Figure 7-8 Combining queries using UNION Note: with UNION queries, the quantity and data types of the attributes in the SELECT clauses of both queries must be identical

27 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 27 This is available with newer versions of SQL, previously not part of the standard Figure 7-9

28 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 28  Be familiar with the data model (entities and relationships)  Understand the desired results  Know the attributes desired in result  Identify the entities that contain desired attributes  Review ERD  Construct a WHERE equality for each link  Fine tune with GROUP BY and HAVING clauses if needed  Consider the effect on unusual data  “Integrity” of logic – do NOT “translate”

29 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Instead of SELECT *, identify the specific attributes in the SELECT clause; this helps reduce network traffic of result set  Limit the number of subqueries; try to make everything done in a single query if possible  If data is to be used many times, make a separate query and store its results rather than performing the query repeatedly 29

30 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Write simple queries  Break complex queries into multiple simple parts  Understand how indexes are used in query processing  Keep optimizer statistics up-to-date  Use compatible data types for fields and literals  Don’t nest one query inside another query  Don’t combine a query with itself (if possible avoid self-joins) 30

31 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Create temporary tables for groups of queries  Combine update operations  Retrieve only the data you need  Don’t have the DBMS sort without an index  Learn!  Consider the total query processing time for ad hoc queries 31

32 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 32  Transaction = A discrete unit of work that must be completely processed or not processed at all  May involve multiple updates  If any update fails, then all other updates must be cancelled  SQL commands for transactions  BEGIN TRANSACTION/END TRANSACTION  Marks boundaries of a transaction  COMMIT  Makes all updates permanent  ROLLBACK  Cancels updates since the last COMMIT

33 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 33 Figure 7-12 An SQL Transaction sequence (in pseudocode) Our lecture may end with this slide

34 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 34  System tables that store metadata  Users usually can view some of these tables  Users are restricted from updating them  Some examples in Oracle 11g  DBA_TABLES – descriptions of tables  DBA_CONSTRAINTS – description of constraints  DBA_USERS – information about the users of the system  Examples in Microsoft SQL Server 2008  sys.columns – table and column definitions  sys.indexes – table index information  sys.foreign_key_columns – details about columns in foreign key constraints

35 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  User-defined data types (UDT)  Subclasses of standard types or an object type  Analytical functions (for OLAP)  CEILING, FLOOR, SQRT, RANK, DENSE_RANK, ROLLUP, CUBE, SAMPLE,  WINDOW–improved numerical analysis capabilities  New Data Types  BIGINT, MULTISET (collection), XML  CREATE TABLE LIKE–create a new table similar to an existing one  MERGE 35

36 Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall  Programming extensions  Persistent Stored Modules (SQL/PSM)  Capability to create and drop code modules  New statements:  CASE, IF, LOOP, FOR, WHILE, etc.  Makes SQL into a procedural language  Oracle has propriety version called PL/SQL, and Microsoft SQL Server has Transact/SQL 36


Download ppt "Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi."

Similar presentations


Ads by Google