C8 - Advanced SQL

Embed Size (px)

Citation preview

  • 8/7/2019 C8 - Advanced SQL

    1/35

    11

    Chapter 8:Chapter 8:Advanced SQLAdvanced SQL

    Modern Database ManagementModern Database Management

    99thth EditionEdition

    Jeffrey A. Hoffer, Mary B. Prescott,Jeffrey A. Hoffer, Mary B. Prescott,

    Heikki TopiHeikki Topi

  • 8/7/2019 C8 - Advanced SQL

    2/35

    22

    ObjectivesObjectives

    Definition of termsDefinition of terms

    Write single and multiple table SQL queriesWrite single and multiple table SQL queries

    Define and use three types of joinsDefine and use three types of joins Write noncorrelated and correlated subqueriesWrite noncorrelated and correlated subqueries

    Establish referential integrity in SQLEstablish referential integrity in SQL

    Understand triggers and stored proceduresUnderstand triggers and stored procedures

    Discuss SQL:200n standard and its extension ofDiscuss SQL:200n standard and its extension ofSQLSQL--9292

    Understand SQL use for OLTP and OLAPUnderstand SQL use for OLTP and OLAP

  • 8/7/2019 C8 - Advanced SQL

    3/35

    33

    Processing Multiple TablesProcessing Multiple TablesJoinsJoins

    JoinJoina relational operation that causes two or more tables with aa relational operation that causes two or more tables with acommon domain to be combined into a single table or viewcommon domain to be combined into a single table or view EquiEqui--joinjoina join in which the joining condition is based ona join in which the joining condition is based on

    equality between values in the common columns; common columnsequality between values in the common columns; common columnsappear redundantly in the result tableappear redundantly in the result table

    Natural joinNatural joinan equian equi--join in which one of the duplicate columnsjoin in which one of the duplicate columnsis eliminated in the result tableis eliminated in the result table Outer joinOuter joina join in which rows that do not have matchinga join in which rows that do not have matching

    values in common columns are nonetheless included in the resultvalues in common columns are nonetheless included in the resulttable (as opposed totable (as opposed to innerinner join, in which rows must have matchingjoin, in which rows must have matchingvalues in order to appear in the result table)values in order to appear in the result table)

    Union joinUnion joinincludes all columns from each table in the join, andincludes all columns from each table in the join, andan instance for each row of each tablean instance for each row of each table

    The common columns in joined tables are usually the primary key of the

    dominant table and the foreign key of the dependent table in 1:M relationships

  • 8/7/2019 C8 - Advanced SQL

    4/35

    44

    Figure 8Figure 8--22

    Visualization of different join types with resultsVisualization of different join types with results

    returned in shaded areareturned in shaded area

    Left outer join: Left watch for the sequence of tables

  • 8/7/2019 C8 - Advanced SQL

    5/35

    55

    The following slides create tables forThe following slides create tables for

    this enterprise data modelthis enterprise data model

  • 8/7/2019 C8 - Advanced SQL

    6/35

    66

    These tables are used in queries that follow

    Figure 8-1 PVFCCustomer and Order tables with pointers

  • 8/7/2019 C8 - Advanced SQL

    7/35

    77

    For each customer who placed an order, what is theFor each customer who placed an order, what is thecustomers name and order number?customers name and order number?

    SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID

    FROM CUSTOMER_T NATURAL JOIN ORDER_T ONFROM CUSTOMER_T NATURAL JOIN ORDER_T ON

    CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

    Join involves multiple tables in FROM clause

    Natural Join ExampleNatural Join Example

    ON clause performs the equality

    check for common columns of the

    two tables

    Note: from Fig. 1, you seethat only 10 Customershave links with orders

    Only 10 rows will bereturned from this INNER

    join

  • 8/7/2019 C8 - Advanced SQL

    8/35

    88

    List the customer name, ID number, and orderList the customer name, ID number, and ordernumber for all customers. Include customernumber for all customers. Include customerinformation even for customers that do have an orderinformation even for customers that do have an order

    SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID

    FROM CUSTOMER_T, LEFT OUTER JOIN ORDER_TFROM CUSTOMER_T, LEFT OUTER JOIN ORDER_T

    ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

    Outer Join ExampleOuter Join Example

    (Microsoft Syntax)(Microsoft Syntax)

    LEFT OUTER JOIN syntax withON causes customer data toappear even if there is nocorresponding order data

    Unlike INNER join, this willinclude customer rows withno matching order rows

    Why Customer data? Why not Order data?

  • 8/7/2019 C8 - Advanced SQL

    9/35

    99

    Results

    UnlikeINNER

    join, thiswill includecustomerrows withno

    matchingorder rows

  • 8/7/2019 C8 - Advanced SQL

    10/35

    1010

    Assemble all information necessary to create anAssemble all information necessary to create aninvoice for order number 1006invoice for order number 1006

    SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME,SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME,CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE,CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE,

    ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY,ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY,PRODUCT_DESCRIPTION, STANDARD_PRICE,PRODUCT_DESCRIPTION, STANDARD_PRICE,(QUANTITY * UNIT_PRICE)(QUANTITY * UNIT_PRICE)

    FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_TFROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T

    WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_IDWHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID

    AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_IDAND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT_PRODUCT_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT_PRODUCT_ID

    AND ORDER_T.ORDER_ID = 1006;AND ORDER_T.ORDER_ID = 1006;

    Four tables involved in this join

    Multiple Table Join ExampleMultiple Table Join Example

    Each pair of tables requires an equality-check condition in the WHERE clause,

    matching primary keys against foreign keys

  • 8/7/2019 C8 - Advanced SQL

    11/35

    1111

    Figure 8-4 Results from a four-tablejoin

    From CUSTOMER_T table

    From ORDER_T table From PRODUCT_T table

  • 8/7/2019 C8 - Advanced SQL

    12/35

    1212

    Processing Multiple TablesProcessing Multiple Tables

    Using SubqueriesUsing Subqueries SubquerySubqueryplacing an inner query (SELECTplacing an inner query (SELECT

    statement) inside an outer querystatement) inside an outer query

    Options:Options:

    In a condition of the WHERE clauseIn a condition of the WHERE clause As a table of the FROM clauseAs a table of the FROM clause

    Within the HAVING clauseWithin the HAVING clause

    Subqueries can be:Subqueries can be:

    NoncorrelatedNoncorrelatedexecuted once for the entireexecuted once for the entireouter queryouter query

    CorrelatedCorrelatedexecuted once for each row returnedexecuted once for each row returnedby the outer queryby the outer query

  • 8/7/2019 C8 - Advanced SQL

    13/35

    1313

    Show all customers who have placed an orderShow all customers who have placed an order

    SELECT CUSTOMER_NAME FROM CUSTOMER_TSELECT CUSTOMER_NAME FROM CUSTOMER_TWHERE CUSTOMER_ID INWHERE CUSTOMER_ID IN

    (SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);

    Subquery ExampleSubquery Example

    Subquery is embedded inparentheses. 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

  • 8/7/2019 C8 - Advanced SQL

    14/35

    1414

    Correlated vs. NoncorrelatedCorrelated vs. Noncorrelated

    SubqueriesSubqueries Noncorrelated subqueries:Noncorrelated subqueries:

    Do not depend on data from the outerDo not depend on data from the outerqueryquery

    Execute once for the entire outer queryExecute once for the entire outer query

    Correlated subqueries:Correlated subqueries: Make use of data from the outer queryMake use of data from the outer query

    Execute once for each row of the outerExecute once for each row of the outerqueryquery

    Can use the EXISTS operatorCan use the EXISTS operator

  • 8/7/2019 C8 - Advanced SQL

    15/35

    1515

    Figure 8-6a

    Processing a

    noncorrelatedsubquery

    No reference to data inouter query, sosubquery executes once

    only

    These are the onlycustomers that haveIDs in the ORDER_Ttable

    1. The subquery

    executes andreturns thecustomer IDs fromthe ORDER_T table

    2. The outer query on

    the results of thesubquery

  • 8/7/2019 C8 - Advanced SQL

    16/35

    1616

    Show all orders that include furniture finished inShow all orders that include furniture finished innatural ashnatural ash

    SELECT DISTINCT ORDER_ID FROM ORDER_LINE_TSELECT DISTINCT ORDER_ID FROM ORDER_LINE_T

    WHERE EXISTSWHERE EXISTS(SELECT * FROM PRODUCT_T(SELECT * FROM PRODUCT_T

    WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_IDWHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID

    AND PRODUCT_FINISH = Natural ash);AND PRODUCT_FINISH = Natural ash);

    Correlated Subquery ExampleCorrelated Subquery Example

    The subquery is testing for a value that comes from the

    outer query further explain: Order-Product-Order

    The EXISTS operator will return a

    TRUE value if the subquery resulted

    in a non-empty set, otherwise itreturns a FALSE

  • 8/7/2019 C8 - Advanced SQL

    17/35

    1717

    Figure 8-6b

    Processing a

    correlatedsubquery

    Subquery refers to outer-

    query data, so executes once

    for each row of outer query

    Note: only theorders thatinvolveproducts withNatural Ash willbe included inthe final results

  • 8/7/2019 C8 - Advanced SQL

    18/35

    1818

    Show all products whose standard price is higher thanShow all products whose standard price is higher than

    the average pricethe average price

    SELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICESELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICE

    FROMFROM(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T),(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T),

    PRODUCT_TPRODUCT_TWHERE STANDARD_PRICE > AVG_PRICE;WHERE STANDARD_PRICE > AVG_PRICE;

    Another Subquery ExampleAnother Subquery Example

    The WHERE clause normally cannot include aggregate functions, but becausethe aggregate is performed in the subquery its result can be used in the outerquerys WHERE clause

    One column of the subquery is anaggregate function that has an aliasname. That alias can then be referredto in the outer query

    Subquery forms the derivedtable used in the FROM clauseof the outer query

  • 8/7/2019 C8 - Advanced SQL

    19/35

    1919

    Union QueriesUnion Queries Combine the output (union of multiple queries)Combine the output (union of multiple queries)

    together into a single result tabletogether into a single result table

    First query

    Second query

    Combine

  • 8/7/2019 C8 - Advanced SQL

    20/35

    2020

    Figure 8-7 Combining queries using UNION

  • 8/7/2019 C8 - Advanced SQL

    21/35

    2121

    Conditional Expressions UsingConditional Expressions Using

    Case SyntaxCase SyntaxThis is available withThis is available with

    newer versions ofnewer versions ofSQL, previously notSQL, previously not

    part of the standardpart of the standard

    Figure 8Figure 8--88

  • 8/7/2019 C8 - Advanced SQL

    22/35

    2222

    Tips for Developing QueriesTips for Developing Queries

    Be familiar with the data model (entities andBe familiar with the data model (entities andrelationships)relationships)

    Understand the desired resultsUnderstand the desired results

    Know the attributes desired in resultKnow the attributes desired in result

    Identify the entities that contain desiredIdentify the entities that contain desiredattributesattributes

    Review ERDReview ERD

    Construct a WHERE for each linkConstruct a WHERE for each link

    Fine tune with GROUP BY and HAVINGFine tune with GROUP BY and HAVINGclauses if neededclauses if needed

    Consider the effect on unusual dataConsider the effect on unusual data

  • 8/7/2019 C8 - Advanced SQL

    23/35

    2323

    Ensuring Transaction IntegrityEnsuring Transaction Integrity

    Transaction = A discrete unit of work thatTransaction = A discrete unit of work thatmust be completely processed or notmust be completely processed or notprocessed at allprocessed at all May involve multiple updatesMay involve multiple updates

    If any update fails, then all other updates must beIf any update fails, then all other updates must becancelledcancelled

    SQL commands for transactionsSQL commands for transactions BEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTION

    Marks boundaries of a transactionMarks boundaries of a transaction

    COMMITCOMMIT Makes all updates permanentMakes all updates permanent

    ROLLBACKROLLBACK Cancels updates since the last COMMITCancels updates since the last COMMIT

  • 8/7/2019 C8 - Advanced SQL

    24/35

    2424

    Figure 8-9An SQL Transaction sequence (in pseudocode)

  • 8/7/2019 C8 - Advanced SQL

    25/35

    2525

    Data Dictionary FacilitiesData Dictionary Facilities

    System tables that store metadataSystem tables that store metadata

    Users usually can view some of these tablesUsers usually can view some of these tables

    Users are restricted from updating themUsers are restricted from updating them

    Some examples in Oracle 10gSome examples in Oracle 10g

    DBA_TABLESDBA_TABLESdescriptions of tablesdescriptions of tables DBA_CONSTRAINTSDBA_CONSTRAINTSdescription of constraintsdescription of constraints

    DBA_USERSDBA_USERSinformation about the users of the systeminformation about the users of the system

    Examples in Microsoft SQL Server 2000Examples in Microsoft SQL Server 2000

    SYSCOLUMNSSYSCOLUMNStable and column definitionstable and column definitions SYSDEPENDSSYSDEPENDSobject dependencies based on foreign keysobject dependencies based on foreign keys

    SYSPERMISSIONSSYSPERMISSIONSaccess permissions granted to usersaccess permissions granted to users

  • 8/7/2019 C8 - Advanced SQL

    26/35

    2626

    SQL:1999 and SQL:200SQL:1999 and SQL:200NN

    Enhancements/ExtensionsEnhancements/Extensions

    UserUser--defined data types (UDT)defined data types (UDT) Subclasses of standard types or an object typeSubclasses of standard types or an object type

    Analytical functions (for OLAP)Analytical functions (for OLAP)

    CEILING, FLOOR, SQRT, RANK, DENSE_RANKCEILING, FLOOR, SQRT, RANK, DENSE_RANK WINDOWWINDOWimproved numerical analysis capabilitiesimproved numerical analysis capabilities

    New Data TypesNew Data Types BIGINT, MULTISET (collection), XMLBIGINT, MULTISET (collection), XML

    CREATE TABLE LIKECREATE TABLE LIKEcreate a new tablecreate a new tablesimilar to an existing onesimilar to an existing one

    MERGEMERGE

  • 8/7/2019 C8 - Advanced SQL

    27/35

    2727

    Persistent Stored Modules (SQL/PSM)Persistent Stored Modules (SQL/PSM)

    Capability to create and drop code modulesCapability to create and drop code modules

    New statements:New statements: CASE, IF, LOOP, FOR, WHILE, etc.CASE, IF, LOOP, FOR, WHILE, etc.

    Makes SQL into a procedural languageMakes SQL into a procedural language

    Oracle has propriety version calledOracle has propriety version calledPL/SQL, and Microsoft SQL Server hasPL/SQL, and Microsoft SQL Server hasTransact/SQLTransact/SQL

    SQL:1999 and SQL:200SQL:1999 and SQL:200NN

    Enhancements/Extensions (cont.)Enhancements/Extensions (cont.)

  • 8/7/2019 C8 - Advanced SQL

    28/35

    2828

    Routines and TriggersRoutines and Triggers

    RoutinesRoutines Program modules that execute on demandProgram modules that execute on demand

    FunctionsFunctionsroutines that return values androutines that return values and

    take input parameterstake input parameters ProceduresProceduresroutines that do not returnroutines that do not return

    values and can take input or outputvalues and can take input or outputparametersparameters

    TriggersTriggers Routines that execute in response to aRoutines that execute in response to a

    database event (INSERT, UPDATE, ordatabase event (INSERT, UPDATE, orDELETE)DELETE)

  • 8/7/2019 C8 - Advanced SQL

    29/35

    2929

    Figure 8-10 Triggers contrasted with stored procedures

    Procedures are called explicitly

    Triggers are event-drivenSource: adapted from Mullins, 1995.

  • 8/7/2019 C8 - Advanced SQL

    30/35

    3030

    Figure 8-11 Simplified trigger syntax, SQL:200n

    Figure 8-12 Create routine syntax, SQL:200n

  • 8/7/2019 C8 - Advanced SQL

    31/35

    3131

    Embedded and Dynamic SQLEmbedded and Dynamic SQL

    Embedded SQLEmbedded SQL

    Including hardIncluding hard--coded SQL statements in acoded SQL statements in aprogram written in another language such asprogram written in another language such asC or JavaC or Java

    Dynamic SQLDynamic SQL

    Ability for an application program to generateAbility for an application program to generate

    SQL code on the fly, as the application isSQL code on the fly, as the application isrunningrunning

  • 8/7/2019 C8 - Advanced SQL

    32/35

    3232

    OLAP SQLOLAP SQL

    Online Transaction Processing (OLTP)Online Transaction Processing (OLTP) RealReal--time processing of SQL transactions,time processing of SQL transactions,

    characterized by fast data entry and retrieval in multicharacterized by fast data entry and retrieval in multi--user environmentsuser environments

    Smaller size, less data sources, many users, simplerSmaller size, less data sources, many users, simplerqueries, more normalized, standard SQLqueries, more normalized, standard SQL

    Online Analytical Processing (OLAP)Online Analytical Processing (OLAP)

    Use of graphical tools providing users withUse of graphical tools providing users with

    multidimensional views of data for analysis purposesmultidimensional views of data for analysis purposes

    Larger size, more data sources, fewer users, complexLarger size, more data sources, fewer users, complexqueries, less normalized, OLAP SQL and statisticalqueries, less normalized, OLAP SQL and statisticalpackages (SPSS/SAS)packages (SPSS/SAS)

  • 8/7/2019 C8 - Advanced SQL

    33/35

    3333

  • 8/7/2019 C8 - Advanced SQL

    34/35

    3434

  • 8/7/2019 C8 - Advanced SQL

    35/35

    3535