Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Copyright © 2007, Oracle. All rights reserved. Introducing the Oracle Database 11g SQL and PL/SQL New Features.

Similar presentations


Presentation on theme: "1 Copyright © 2007, Oracle. All rights reserved. Introducing the Oracle Database 11g SQL and PL/SQL New Features."— Presentation transcript:

1 1 Copyright © 2007, Oracle. All rights reserved. Introducing the Oracle Database 11g SQL and PL/SQL New Features

2 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Describe the organization of the course Review the schemas that are used in this course Review the SQL*Plus environment that you can optionally use in this course Find additional information about Oracle Database 11g on the Oracle Technology Network

3 Copyright © 2007, Oracle. All rights reserved Course Objectives After completing this course, you should be able to: Use the SQL Developer interface with the latest enhancements Write SQL statements that include the new functions added to enhance regular expression support functionality Monitor dependency tracking and change notification List the changes to locking that enable you to specify the maximum number of seconds the statement should wait to obtain a DML lock on the table Practice the performance improvements

4 Copyright © 2007, Oracle. All rights reserved Course Objectives Use the enhancements added to native dynamic SQL and to DBMS_SQL, which enable more interoperability between the two methodologies Write compound triggers and use the enhancements made to the triggers Use SecureFile LOBS Write SQL and PL/SQL calls to sequences that are simpler Use the new CONTINUE statement to control loops Explore the data warehousing improvements

5 Copyright © 2007, Oracle. All rights reserved Course Agenda Day 1: Introducing Oracle Database 11g SQL and PL/SQL enhancements Using the SQL Developer enhancements Using the language functionality enhancements Executing dynamic SQL in PL/SQL with the 11g enhancements Implementing the performance improvements

6 Copyright © 2007, Oracle. All rights reserved Course Agenda Day 2: Practicing the language usability enhancements Developing triggers that utilize the new enhancements Administering SecureFile LOBs Using the data warehousing usability enhancements

7 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Appendixes and tables used in this course Overview of SQL*Plus Oracle Database 11g documentation and additional resources

8 Copyright © 2007, Oracle. All rights reserved Appendixes Used in This Course Appendix A: Practice Solutions Appendix B: Table Descriptions Appendix C: Using Oracle SQL Developer Appendix D: SQL*Plus Appendix E: Working with Collections Appendix F: Exploring the Data Warehousing Performance Enhancements

9 Copyright © 2007, Oracle. All rights reserved Tables Used in This Course The sample schemas that are used in this course are: The Order Entry ( OE ) schema The Sales History (SH) schema

10 Copyright © 2007, Oracle. All rights reserved Order Entry (OE) Schema WAREHOUSES warehouse_id warehouse_name location_id ORDERS order_id order_date order_mode customer_id order_status order_total sales_rep_id promotion_id ORDER_ITEMS order_id line_item_id product_id unit_price quantity PRODUCT_ INFORMATION product_id product_name product_description category_id weight_class warranty_period supplier_id product_status list_price min_price catalog_url CUSTOMERS customer_id cust_first_name cust_ last_name cust_ address_typ phone_numbers nls_language nls_territory credit_limit cust_ account_mgr_id date_of_birth marital_status gender Income_level street_address postal_code city state_province country_id PRODUCT_ DESCRIPTIONS product_id language_id product_name product_description INVENTORIES product_id warehouse_id quantity_on_hand

11 Copyright © 2007, Oracle. All rights reserved Sales History (SH) Schema COSTS prod_id time_id promo_id channel_id unit_cost unit_price PROMOTIONS promo_id promo_name promo_subcategory promo_subcategory_id promo_category promo_category_id promo_cost promo_begin_date promo_end_date promo_total promo_total_id SALES prod_id cust_id time_id channel_id promo_id quantity_sold amount_sold CHANNELS channel_id channel_desc channel_class channel_class_id channel_total channel_total_id TIMES time_id day_name day_number_in_week day_number_in_month calendar_week_number fiscal_week_number week_ending_day week_ending_day_id calendar_month_number fiscal_month_number calendar_month_desc calendar_month_id fiscal_month_id days_in_cal_month days_in_fis_month end_of_cal_ month end_of_fis_month calendar _month _name fiscal _month _name calendar _quarter _desc calendar_quarter_id fiscal _quarter _desc fiscal _quarter _id days_in_cal_quarter days_in_fis_quarter end_of_cal_quarter end_of_fis_quarter calendar_quarter_number fiscal_quarter_number calendar_year calendar_year_id fiscal_year fiscal_year_id days_in_cal_year days_in_fis_year end_of_cal_year end_of_fis_year PRODUCTS

12 Copyright © 2007, Oracle. All rights reserved Sales History (SH) Schema PRODUCTS prod_id prod_name prod_desc prod_subcategory prod_subcategory_id prod_subcategory_desc prod_category prod_category_id prod_category_desc prod_weight_class prod_unit_of_measure prod_pack_size supplier_id prod_status prod_list_price prod_min_price prod_total prod_total_id prod_src_id prod_eff_from prod_eff_to prod_valid CUSTOMERS cust_id cust_first_name cust_last_name cust_gender cust_year_of_birth cust_marital_status cust_street_address cust_postal_code cust_city cust_city_id cust_state_province cust_state_province_id country_id cust_main_phone_number cust_income_level cust_credit_limit cust_ cust_total cust_total_id cust_src_id cust_eff_from cust_eff_to cust_valid COUNTRIES country_id country_iso_code country_name country_subregion country_subregion_id country_region country_region_id country_total country_total_id Country_name_hist COSTSSALES

13 Copyright © 2007, Oracle. All rights reserved Class Account Information Cloned OE account IDs are set up for you. Your account IDs are OE1 – OE20. The password matches your account ID. Each machine is assigned one account. All OE account IDs have SELECT status on the SH schema. The instructor has a separate ID.

14 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Appendixes and tables used in this course Overview of SQL*Plus Oracle Database 11g documentation and additional resources

15 Copyright © 2007, Oracle. All rights reserved Overview of SQL*Plus Used in This Course Logging in to SQL*Plus Describing the table structure Executing SQL from SQL*Plus Reviewing SQL*Plus file commands

16 Copyright © 2007, Oracle. All rights reserved sqlplus Logging In to SQL*Plus 1 2

17 Copyright © 2007, Oracle. All rights reserved Displaying Table Structure DESCRIBE sh.customers Name Null? Type CUST_ID NOT NULL NUMBER CUST_FIRST_NAME NOT NULL VARCHAR2(20) CUST_LAST_NAME NOT NULL VARCHAR2(40) CUST_GENDER NOT NULL CHAR(1) CUST_YEAR_OF_BIRTH NOT NULL NUMBER(4) CUST_MARITAL_STATUS VARCHAR2(20) CUST_STREET_ADDRESS NOT NULL VARCHAR2(40) CUST_POSTAL_CODE NOT NULL VARCHAR2(10) CUST_CITY NOT NULL VARCHAR2(30) CUST_CITY_ID NOT NULL NUMBER CUST_STATE_PROVINCE NOT NULL VARCHAR2(40) CUST_STATE_PROVINCE_ID NOT NULL NUMBER COUNTRY_ID NOT NULL NUMBER CUST_MAIN_PHONE_NUMBER NOT NULL VARCHAR2(25) CUST_INCOME_LEVEL VARCHAR2(30) CUST_CREDIT_LIMIT NUMBER CUST_ VARCHAR2(30) CUST_TOTAL NOT NULL VARCHAR2(14) CUST_TOTAL_ID NOT NULL NUMBER...

18 Copyright © 2007, Oracle. All rights reserved Executing SQL from SQL*Plus CUST_LAST_NAME G INCOME_LEVEL Kinski M D: 70, ,999 Garcia F I: 170, ,999 Olin F F: 110, ,999 Altman F F: 110, ,999 de Funes F D: 70, ,999 Chapman F F: 110, ,999 Gielgud F E: 90, ,999 Prashant F C: 50, ,999 Welles M D: 70, ,999 Rampling M F: 110, , rows selected. SELECT cust_last_name, cust_gender, cust_income_level FROM sh.customers;

19 Copyright © 2007, Oracle. All rights reserved SQL*Plus File Commands SAVE filename GET filename START EDIT filename SPOOL filename EXIT

20 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Appendixes and tables used in this course Overview of SQL*Plus Overview of Oracle SQL Developer Oracle Database 11g documentation and additional resources

21 Copyright © 2007, Oracle. All rights reserved Oracle Database 11g SQL and PL/SQL Documentation Navigate to then click the Books tab:http://www.oracle.com/pls/db111/homepage Oracle Database Advanced Application Developers Guide 11g, Release 1 (11.1) Oracle Database Concepts 11g, Release 1 (11.1) Oracle Database 2 Day Developers Guide 11g, Release 1 (11.1) Oracle Database Security Guide 11g, Release 1 (11.1)

22 Copyright © 2007, Oracle. All rights reserved Oracle Database 11g SQL and PL/SQL Documentation Oracle Database SQL Language Reference 11g, Release 1 Oracle Database PL/SQL Language Reference 11g, Release 1 Oracle Database PL/SQL Packages and Types Reference 11g, Release 1 Oracle Database Large Objects Developers Guide SQL*Plus Users Guide and Reference Oracle Database SQL Developer Users Guide, Release 1.2

23 Copyright © 2007, Oracle. All rights reserved Additional Resources For additional information about the new Oracle 11g SQL and PL/SQL new features, refer to the following: Oracle Database 11g: New Features eStudies Oracle by Example series (OBE): Oracle Database 11g –http://www.oracle.com/technology/obe/11gr1_db/admin/ 11gr1db.html Whats New in PL/SQL in Oracle Database 11g on the Oracle Technology Network (OTN): –http://www.oracle.com/technology/tech/pl_sql/

24 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Describe the organization of the course Review the schemas that are used in this course Review the SQL*Plus environment that you can optionally use in this course Find additional information about Oracle Database 11g from the Oracle Technology Network

25 Copyright © 2007, Oracle. All rights reserved Practice 1 Overview: Getting Started This practice covers the following topics: Reviewing the schemas for this course Using SQL*Plus Accessing Oracle Database 11g resources

26 Copyright © 2007, Oracle. All rights reserved Notes Page Only

27 2 Copyright © 2007, Oracle. All rights reserved. Using SQL Developer

28 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: List the key features of Oracle SQL Developer Install Oracle SQL Developer Create a database connection Navigate through the object navigator Use the SQL Worksheet Create, save, and use scripts Develop, compile, and debug PL/SQL Browse through the available search engines Change preferences Create reports Describe migration

29 Copyright © 2007, Oracle. All rights reserved What Is Oracle SQL Developer? Oracle SQL Developer is a free graphical tool that enhances productivity and simplifies database development tasks. You can connect to any target Oracle database schema using standard Oracle database authentication. SQL Developer

30 Copyright © 2007, Oracle. All rights reserved Installing SQL Developer Download the Oracle SQL Developer kit and unzip it into any directory on your machine.

31 Copyright © 2007, Oracle. All rights reserved Menus for SQL Developer

32 Copyright © 2007, Oracle. All rights reserved Creating a Database Connection You must have at least one database connection to use SQL Developer. You can create and test connections for: –Multiple databases –Multiple schemas SQL Developer automatically reads any connections defined in the tnsnames.ora file on your system. You can export connections to an XML file. Each additional database connection created is listed in the Connections navigator hierarchy.

33 Copyright © 2007, Oracle. All rights reserved Creating a Database Connection

34 Copyright © 2007, Oracle. All rights reserved Browsing Database Objects Use the Database navigator to: Browse through many objects in a database schema Review the definitions of objects at a glance

35 Copyright © 2007, Oracle. All rights reserved Exporting Database Objects Enter the file name destination, and select the Connection. Select the Objects to export. Click Apply.

36 Copyright © 2007, Oracle. All rights reserved Exporting Database Objects The resulting file contains the object definitions you exported.

37 Copyright © 2007, Oracle. All rights reserved Exporting and Importing Data

38 Copyright © 2007, Oracle. All rights reserved Using SQL Worksheet Use SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus statements. Specify any actions that can be processed by the database connection associated with the worksheet.

39 Copyright © 2007, Oracle. All rights reserved Using SQL Worksheet

40 Copyright © 2007, Oracle. All rights reserved Executing SQL Statements Use the Enter SQL Statement box to enter single or multiple SQL statements. View the results on the Script Output tabbed page.

41 Copyright © 2007, Oracle. All rights reserved Saving SQL Scripts Click the Save icon to save your SQL statement to a file. The contents of the saved file are visible and editable in your SQL Worksheet window. Enter a file name and identify a location to save the file in the Windows Save dialog box.

42 Copyright © 2007, Oracle. All rights reserved Executing Saved SQL Scripts Use command followed by the location and name of the file you want to execute. Then click the Run Script icon. The output from the script is displayed on the Script Output tabbed page.

43 Copyright © 2007, Oracle. All rights reserved Using PL/SQL in SQL Developer Right-click the Procedures node and select New Procedure.

44 Copyright © 2007, Oracle. All rights reserved Using PL/SQL in SQL Developer Enter the header information for the procedure, and then click OK. Enter your code.

45 Copyright © 2007, Oracle. All rights reserved Using PL/SQL in SQL Developer Click Compile. Compilation messages are displayed on Messages – Log.

46 Copyright © 2007, Oracle. All rights reserved Using PL/SQL in SQL Developer Click Run. The Run dialog box appears with a call to your code wrapped within an anonymous block. Enter the parameter values, and then click OK.

47 Copyright © 2007, Oracle. All rights reserved Using PL/SQL in SQL Developer Enter the parameter values, and then click OK. The results are displayed on the Running – Log tabbed page.

48 Copyright © 2007, Oracle. All rights reserved Browsing Through the Available Search Engines Select a search engine. Enter a search word, and then press [Enter]. The results are displayed in your browser.

49 Copyright © 2007, Oracle. All rights reserved Changing Preferences From the Tools menu, select Preferences. The Preferences dialog box appears.

50 Copyright © 2007, Oracle. All rights reserved Creating Reports SQL Developer provides you with a number of predefined reports about your database and objects. The reports are organized into categories. You can create your own customized reports too.

51 Copyright © 2007, Oracle. All rights reserved Creating Reports

52 Copyright © 2007, Oracle. All rights reserved Creating PL/SQL Reports Select a connection, and then click OK. Select the PL/SQL report type.

53 Copyright © 2007, Oracle. All rights reserved Searching PL/SQL Code Specify either an Object Name search or a Text Search. Enter the value to search and click Apply. The results are displayed.

54 Copyright © 2007, Oracle. All rights reserved Creating a User-Defined Report Create and save user-defined reports for repeated use. Organize reports in folders

55 Copyright © 2007, Oracle. All rights reserved Using SQL*Plus You can invoke the SQL*Plus command-line interface from SQL Developer. Close all SQL Worksheets to enable the SQL*Plus menu option. Provide the location of the sqlplus.exe file only for the first time you invoke SQL*Plus.

56 Copyright © 2007, Oracle. All rights reserved Introducing Migration Through SQL Developer Reduces the effort and risks involved in a migration project Enables you to migrate an entire third-party database, including triggers and stored procedures Enables you to see and compare the captured model and the converted model, and to customize each Provides feedback about the migration through reports Oracle

57 Copyright © 2007, Oracle. All rights reserved Migration in SQL Developer Destination Oracle schema Captured model Converted model Migration repository Source data SQL Developer

58 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: List the key features of Oracle SQL Developer Install Oracle SQL Developer Create a database connection Navigate through the object navigator Use the SQL Worksheet Create, save, and use scripts Develop, compile, and debug PL/SQL Browse through the available search engines Change preferences Create reports Describe migration

59 Copyright © 2007, Oracle. All rights reserved Practice 2 Overview: Using SQL Developer This practice covers the following topics: Starting SQL Developer Creating a database connection in SQL Developer Executing SQL statements Setting up your script pathing preference Creating, compiling, and debugging a procedure Examining exporting Creating a SQL report Setting up and accessing SQL*Plus

60 Copyright © 2007, Oracle. All rights reserved Notes Page Only

61 Copyright © 2007, Oracle. All rights reserved Notes Page Only

62 Copyright © 2007, Oracle. All rights reserved Notes Page Only

63 Copyright © 2007, Oracle. All rights reserved Notes Page Only

64 Copyright © 2007, Oracle. All rights reserved Notes Page Only

65 3 Copyright © 2007, Oracle. All rights reserved. Using the Language Functionality Enhancements

66 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Use the new regular expression support functions Track dependencies at the element level Find and fix exception handlers that do not pass the exception upward Dispatch an overridable object type method Learn about Data Change Notification (DCN) result-set- change notification Use the lock enhancements: –Use the LOCK TABLE … WAIT new syntax –Set the DDL_LOCK_TIMEOUT parameter

67 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

68 Copyright © 2007, Oracle. All rights reserved Regular Expression Enhancements in SQL and PL/SQL Features added: 1.Access to the n-th subexpression in the REGEXP_INSTR and REGEXP_SUBSTR functions 2.Return the number of times a pattern match is found in an input string using the new REGEXP_COUNT function Benefits: –Extends the current regular expression functionality based on customer feedback –Decreases the number of calls to the regular expression functions in order to get related information

69 Copyright © 2007, Oracle. All rights reserved Understanding Subexpressions Examine this expression: The subexpressions are: (1 2 3)(4(5 6)(7 8))

70 Copyright © 2007, Oracle. All rights reserved Using Subexpressions with Regular Expression Support SELECT REGEXP_INSTR (' ', -- source char or search value '(123)(4(56)(78))', -- regular expression patterns 1, -- position to start searching 1, -- occurrence 0, -- return option 'i', -- match option (case insensitive) 1) -- subexpression on which to search "Position" FROM dual; Position REGEXP_INSTR and REGEXP_SUBSTR now have an optional subexpr parameter that lets you target a particular substring of the regular expression being evaluated.

71 Copyright © 2007, Oracle. All rights reserved Using Subexpressions with Regular Expression Support: More Examples SELECT REGEXP_INSTR(' ', '(123)(4(56)(78))', 1, 1, 0, 'i', 2) "Position" FROM dual; Position SELECT REGEXP_INSTR(' ', '(123)(4(56)(78))', 1, 1, 0, 'i', 4) "Position" FROM dual; Position

72 Copyright © 2007, Oracle. All rights reserved Why Access the n-th Subexpression? A more realistic use: DNA sequencing You may need to find a specific subpattern that identifies a protein needed for immunity in mouse DNA. CREATE OR REPLACE FUNCTION get_instrsubexp_pos (p_subexp NUMBER)RETURN NUMBER IS v_dna CLOB; v_location NUMBER; BEGIN v_dna := ' ccacctttccctccactcctcacgttctcacctgtaaagcgtccctccctcatccccatgcccccttac cctgcagggtagagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcagagagag gagaatttgccccaaagctgcctgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttctt gagttttcaccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagaggctc ttgggtctgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggcatgtaggggcgtgggga tgcgctctgctctgctctcctctcctgaacccctgaaccctctggctaccccagagcacttagagccag '; v_location := REGEXP_INSTR(v_dna, '(gtc(tcac)(aaag))', 1, 1, 0, 'i', p_subexp); RETURN (v_location); END;

73 Copyright © 2007, Oracle. All rights reserved REGEXP_INSTR : Examples SQL> EXECUTE dbms_output.put_line(get_instrsubexp_pos(1)); 197 PL/SQL procedure successfully completed. SQL> EXECUTE dbms_output.put_line(get_instrsubexp_pos(2)); 200 PL/SQL procedure successfully completed. SQL> EXECUTE dbms_output.put_line(get_instrsubexp_pos(3)); 204 PL/SQL procedure successfully completed

74 Copyright © 2007, Oracle. All rights reserved REGEXP_SUBSTR : Example REGEXP_SUBSTR searches for a regular expression pattern within a given string and returns the matched string. SELECT REGEXP_SUBSTR ('acgctgcactgca', -- source char or search value 'acg(.*)gca', -- regular expression pattern 1, -- position to start searching 1, -- occurrence 'i', -- match option (case insensitive) 1) -- subexpression Value" FROM dual; Value ctgact

75 Copyright © 2007, Oracle. All rights reserved REGEXP_COUNT Function Returns the number of times a pattern appears in a string CREATE OR REPLACE FUNCTION get_subexp_count (p_subexp VARCHAR2)RETURN NUMBER IS v_dna CLOB; v_count NUMBER; BEGIN v_dna := ' ccacctttccctccactcctcacgttctcacctgtaaagcgtccctccctcatccccatgcccccttaccctgcag ggtagagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcagagagaggagaat ttgccccaaagctgcctgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagttttcacc ctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagaggctcttgggtctgatggcca catcctggaattgttttcaagttgatggtcacagccctgaggcatgtaggggcgtggggatgcgctctgctctgctctcct ctcctgaacccctgaaccctctggctaccccagagcacttagagccag '; v_count := REGEXP_COUNT(v_dna, p_subexp); RETURN (v_count); END;

76 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

77 Copyright © 2007, Oracle. All rights reserved More Precise Dependency Metadata Earlier releases recorded dependency metadata. Oracle Database 11g records additional, finer-grained dependency management. Prior to Oracle Database 11g, adding column D to table T invalidated the dependent objects. Starting in Oracle Database 11g, adding column D to table T does not impact view V and does not invalidate the dependent objects. Procedure P Function F View V Column A Column B Table T Column A Column B Add Column D

78 Copyright © 2007, Oracle. All rights reserved Fine-Grain Dependency Management In Oracle Database 11g, dependencies are tracked at the level of element within unit. Element-based dependency tracking covers the following: Dependency of a single-table view on its base table Dependency of a PL/SQL program unit (package specification, package body, or subprogram) on the following: –Other PL/SQL program units –Tables –Views

79 Copyright © 2007, Oracle. All rights reserved SQL Fine-Grain Dependency Management: Example CREATE TABLE t (col_a NUMBER, col_b NUMBER, col_c NUMBER); CREATE VIEW v AS SELECT col_a, col_b FROM T; SELECT ud.name, ud.type, ud.referenced_name, ud.referenced_type, uo.status FROM user_dependencies ud, user_objects uo WHERE ud.name = uo.object_name AND ud.name = 'V'; NAME TYPE REFERENCED_NAME REFERENCED_TYPE STATUS V VIEW T TABLE VALID ALTER TABLE t ADD (col_d VARCHAR2(20)); SELECT ud.name, ud.type, ud.referenced_name, ud.referenced_type, uo.status FROM user_dependencies ud, user_objects uo WHERE ud.name = uo.object_name AND ud.name = 'V'; NAME TYPE REFERENCED_NAME REFERENCED_TYPE STATUS V VIEW T TABLE VALID 1 2

80 Copyright © 2007, Oracle. All rights reserved SQL Fine-Grain Dependency Management: Example CREATE TABLE t (col_a NUMBER, col_b NUMBER, col_c NUMBER); CREATE OR REPLACE VIEW v AS SELECT col_a, col_b FROM T; SELECT ud.name, ud.referenced_name, ud.referenced_type, uo.status FROM user_dependencies ud, user_objects uo WHERE ud.name = uo.object_name AND ud.name = 'V'; NAME REFERENCED_NAME REFERENCED_TYPE STATUS V VIEW T TABLE VALID ALTER TABLE t MODIFY (col_a VARCHAR2(20)); SELECT ud.name, ud.referenced_name, ud.referenced_type, uo.status FROM user_dependencies ud, user_objects uo WHERE ud.name = uo.object_name AND ud.name = 'V'; NAME REFERENCED_NAME REFERENCED_TYPE STATUS V VIEW T TABLE INVALID

81 Copyright © 2007, Oracle. All rights reserved PL/SQL Fine-Grain Dependency Management: Example CREATE PACKAGE sample_pkg IS PROCEDURE p1; END sample_pkg; / CREATE PROCEDURE my_proc IS BEGIN sample_pkg.p1(); END my_proc ; / CREATE OR REPLACE PACKAGE sample_pkg IS PROCEDURE p1; PROCEDURE unheard_of; END sample_pkg; / SELECT status FROM user_objects WHERE object_name = 'MY_PROC'; STATUS VALID

82 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

83 Copyright © 2007, Oracle. All rights reserved PLW Warning A new PLW warning is available to you. This warning means that the OTHERS handler of your PL/SQL subroutine can exit without executing some form of RAISE or a call to the standard RAISE_APPLICATION_ERROR procedure. Good programming practices suggest that the OTHERS handler must always pass an exception upward.

84 Copyright © 2007, Oracle. All rights reserved PLW Warning: Example CREATE OR REPLACE PROCEDURE p (i IN VARCHAR2) IS BEGIN INSERT INTO t(col_a) VALUES (i); EXCEPTION WHEN OTHERS THEN null; END p; / ALTER PROCEDURE P COMPILE PLSQL_warnings = 'enable:all' REUSE SETTINGS; SP2-0805: Procedure altered with compilation warnings SQL> SHOW ERRORS Errors for PROCEDURE P: LINE/COL ERROR /10 PLW-06009: procedure "P" OTHERS handler does not end in RAISE or RAISE_APPLICATION_ERROR

85 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

86 Copyright © 2007, Oracle. All rights reserved Support for Generalized Invocation Provides the ability to statically dispatch an overridable object type method Is compliant with ANSI SQL 2003 Adds new syntax to PL/SQL to support this feature A Supertype C Subtype of B D Subtype of A B Subtype of A Supertype of C

87 Copyright © 2007, Oracle. All rights reserved Support for Generalized Invocation: Example The Employee_t supertype has an overridable show_data() member function that displays generic employee information: CREATE OR REPLACE TYPE employee_t AS OBJECT( emp_id NUMBER, emp_last_name VARCHAR2(100), emp_salary NUMBER, MEMBER PROCEDURE show_data) NOT FINAL NOT INSTANTIABLE / CREATE OR REPLACE TYPE BODY employee_t IS MEMBER PROCEDURE show_data IS BEGIN DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_id || ' Last name: ' || emp_last_name || ' Salary: ' || emp_salary); END show_data; END; /

88 Copyright © 2007, Oracle. All rights reserved Support for Generalized Invocation: Example The Salesperson_t subtype specializes the show_data() method to acknowledge notions such as territory covered: CREATE OR REPLACE TYPE salesperson_t UNDER employee_t ( territory VARCHAR2(100), OVERRIDING MEMBER PROCEDURE show_data) FINAL / CREATE OR REPLACE TYPE BODY salesperson_t IS OVERRIDING MEMBER PROCEDURE show_data IS BEGIN -- First form of the new syntax. show_data((SELF AS employee_t)); DBMS_OUTPUT.PUT_LINE('Sales Territory: ' || territory); END show_data; END; /

89 Copyright © 2007, Oracle. All rights reserved Support for Generalized Invocation: Example The Developer_t subtype specializes the show_data() method to acknowledge notions such as product area of responsibility: CREATE OR REPLACE TYPE developer_t UNDER employee_t( product_line VARCHAR2(100), OVERRIDING MEMBER PROCEDURE show_data) FINAL / CREATE OR REPLACE TYPE BODY developer_t IS OVERRIDING MEMBER PROCEDURE show_data IS BEGIN -- Second form (and more natural form) of the new syntax. (SELF AS employee_t).show_data(); DBMS_OUTPUT.PUT_LINE('Product Area: '|| product_line); END show_data; END; /

90 Copyright © 2007, Oracle. All rights reserved Support for Generalized Invocation: Example Create a tester program to try out the new functionality: CREATE OR REPLACE PROCEDURE Test_It IS TYPE employee_List_t IS TABLE OF employee_t INDEX BY PLS_INTEGER; emp_Objects employee_List_t; BEGIN -- create some sample data for this example: emp_objects(1) := salesperson_t(35, 'Patel', 90000, 'India' ); emp_Objects(2) := salesperson_t(30, 'Jones', 92000, 'UK'); emp_objects(3) := developer_t(25, 'Cline', 96000, '11g XML'); emp_Objects(4) := developer_t(20, 'Smith', 97000, '11g PL/SQL'); FOR j IN 1..emp_objects.Count() LOOP DBMS_OUTPUT.PUT_LINE('Employee Report for: '); emp_Objects(j).show_data(); DBMS_OUTPUT.PUT_LINE(chr(10)); END LOOP; END; / BEGIN Test_It(); END; /

91 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

92 Copyright © 2007, Oracle. All rights reserved Overview of Data Change Notification Enhancements Pre-Oracle Database 11g, Release 11.1: –Only object-change notifications, which result from DML or DDL changes to the objects associated with the registered queries are published. Starting with Oracle Database 11g, Release 11.1: –Result-set-change notifications, which result from DML or DDL changes to the result set associated with the registered queries are published. –New static data dictionary views allow you to see which queries are registered for result-set-change notifications.

93 Copyright © 2007, Oracle. All rights reserved Notes Page Only

94 Copyright © 2007, Oracle. All rights reserved Data Change Notification Process Client application Data Dictionary PL/SQL Job Queue process Middle Tier Invalidation queue User objects Web cache Client notification Registration via PL/SQL or OCI DML Oracle Database

95 Copyright © 2007, Oracle. All rights reserved Data Change Notification With object change notification: –DNS generates an object-change notification for this query for any DML or DDL change to the ORDERS table, even if the changed row or rows did not satisfy the query predicate (for example, if sales_rep_id = 160 ) With result-set-change notification: –DNS generates a result-set-change notification only if the query result set itself changed and both of the following are true: The changed row or rows satisfy the query predicate (sales_rep_id = 158) either before or after the change. The change affected at least one of the columns in the SELECT list ( order_id or order_total ), as the result of either an UPDATE or an INSERT. SELECT order_id, order_total FROM orders WHERE sales_rep_id = 158;

96 Copyright © 2007, Oracle. All rights reserved Data Dictionary Views for CQN To see top-level information about all registrations: – DBA_CHANGE_NOTIFICATION_REGS – USER_CHANGE_NOTIFICATION_REGS To see which queries are registered for result-set-change notifications: – DBA_CQ_NOTIFICATION_QUERIES – USER_CQ_NOTIFICATION_QUERIES

97 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Using the new regular expression support functions Tracking dependencies at the element level Fixing exception handlers that do not pass the exception upward Dispatching an overridable object type method Learning about Data Change Notification (DCN) result-set- change notification Utilizing the lock enhancements –Using the LOCK TABLE … WAIT new syntax –Setting the DDL_LOCK_TIMEOUT parameter

98 Copyright © 2007, Oracle. All rights reserved Using the LOCK TABLE Statement with the WAIT Option Use the WAIT option to identify the maximum number of seconds a statement should wait to obtain a DML lock on the table. There is no limit on the number of seconds. A message is returned indicating that the object is already locked.

99 Copyright © 2007, Oracle. All rights reserved Using the LOCK TABLE Statement with the WAIT Option: Example In session #1: LOCK TABLE orders IN EXCLUSIVE MODE; In session #2: LOCK TABLE orders IN EXCLUSIVE MODE WAIT 60; ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired Time

100 Copyright © 2007, Oracle. All rights reserved Setting the DDL_LOCK_TIMEOUT Parameter Use the DDL_LOCK_TIMEOUT parameter to specify a DDL lock timeout. –The permissible range of values for DDL_LOCK_TIMEOUT is 0 through 1,000,000 (in seconds). –The default is 0. You can set DDL_LOCK_TIMEOUT at the: –System level –Session level (with an ALTER SESSION statement)

101 Copyright © 2007, Oracle. All rights reserved Setting the DDL_LOCK_TIMEOUT Parameter: Example System level: Session level: DDL_LOCK_TIMEOUT = ALTER SESSION SET DDL_LOCK_TIMEOUT = 50000;

102 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Use the new regular expression support functions Track dependencies at the element level Find and fix exception handlers that do not pass the exception upward Dispatch an overridable object type method Learn about Data Change Notification (DCN) result-set- change notification Use the lock enhancements

103 Copyright © 2007, Oracle. All rights reserved Practice 3 Overview: Using the Language Functionality Enhancements This practice covers the following topics: Using the regular expression support new functions for find and count patterns Tracking dependencies at the element level Writing code that causes the new PLW warning and then fix the code Trying the WAIT option for DDL statements

104 Copyright © 2007, Oracle. All rights reserved Notes Page Only

105 Copyright © 2007, Oracle. All rights reserved Notes Page Only

106 Copyright © 2007, Oracle. All rights reserved Notes Page Only

107 Copyright © 2007, Oracle. All rights reserved Notes Page Only

108 Copyright © 2007, Oracle. All rights reserved Notes Page Only

109 4 Copyright © 2007, Oracle. All rights reserved. Executing Dynamic SQL in PL/SQL with the 11g Enhancements

110 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Write PL/SQL code that uses dynamic SQL and allows for SQL statements larger than 32 KB Use the DBMS_SQL.PARSE() function that is overloaded for CLOBs Convert a REF CURSOR to a DBMS_SQL cursor and vice versa to support interoperability Program using the enhancements to DBMS_SQL that include supporting the full range of data types (including collections and object types)

111 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Overview of native dynamic SQL and DBMS_SQL –Introduction –Previous limitations Dynamic SQL support for CLOBs –Native dynamic SQL support for CLOBs – DBMS_SQL.PARSE() for CLOBs Converting between a REF CURSOR and a DBMS_SQL cursor – DBMS_SQL.TO_REF_CURSOR – DBMS_SQL.TO_CURSOR_NUMBER DBMS_SQL support for abstract data types

112 Copyright © 2007, Oracle. All rights reserved Native Dynamic SQL and DBMS_SQL : Overview Native dynamic SQL and the DBMS_SQL package are two ways to implement a dynamic SQL statement programmatically. You use native dynamic SQL on a single operation to bind any arguments in the dynamic SQL statement and execute the statement. You use the DBMS_SQL package to execute a dynamic SQL statement that has an unknown number of input or output variables.

113 Copyright © 2007, Oracle. All rights reserved Native Dynamic SQL and DBMS_SQL : Overview Use native dynamic SQL when: –The dynamic SQL statement retrieves rows into records –You want to use the %FOUND, %ISOPEN, %NOTFOUND, or %ROWCOUNT SQL cursor attributes after issuing a dynamic SQL statement that is an INSERT, UPDATE, DELETE, or single-row SELECT statement Use DBMS_SQL when: –You do not know the SELECT list at compile time –You do not know how many columns a SELECT statement will return, or what their data types are

114 Copyright © 2007, Oracle. All rights reserved Dynamic SQL Functional Completeness Currently have two flavors of dynamic SQL within PL/SQL: DBMS_SQL and native dynamic SQL For functional completeness, interoperability between native dynamic SQL and DBMS_SQL is supported: –SQL statements larger than 32 KB are allowed in native dynamic SQL. – DBMS_SQL.PARSE() is overloaded for CLOBs. –A REF CURSOR can be converted to a DBMS_SQL cursor and vice versa to support interoperability. – DBMS_SQL supports the full range of data types (including collections and object types).

115 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Overview of native dynamic SQL and DBMS_SQL –Introduction –Previous limitations Dynamic SQL support for CLOBs –Native dynamic SQL support for CLOBs – DBMS_SQL.PARSE() for CLOBs Converting between a REF CURSOR and a DBMS_SQL cursor – DBMS_SQL.TO_REF_CURSOR – DBMS_SQL.TO_CURSOR_NUMBER DBMS_SQL support for abstract data types

116 Copyright © 2007, Oracle. All rights reserved EXECUTE gen_pl('begin dbms_output.put_line – (''put any code here''); end;') put any code here Just executed the following code: begin dbms_output.put_line('put any code here'); end; PL/SQL procedure successfully completed. Dynamic SQL Support for CLOBs Native dynamic SQL support: CREATE OR REPLACE PROCEDURE gen_pl (p_pgm CLOB) IS dynamic_pl CLOB := p_pgm; BEGIN EXECUTE IMMEDIATE dynamic_pl; -- next line is for learning purposes only DBMS_OUTPUT.PUT_LINE ('Just executed the following code: ' || dynamic_pl); END gen_pl; 1 2

117 Copyright © 2007, Oracle. All rights reserved Dynamic SQL Support for CLOBs More native dynamic SQL examples: For symmetry, DBMS_SQL.PARSE now accepts a CLOB too. EXECUTE gen_pl('begin null; end;') Just executed the following code: begin null; end; PL/SQL procedure successfully completed. EXECUTE gen_pl('begin dbms_output.put_line(''hello world''); end;') hello world! Just executed the following code: begin dbms_output.put_line('hello world!'); end; PL/SQL procedure successfully completed. PROCEDURE parse (c IN INTEGER, statement IN CLOB, language_flag IN INTEGER); 4 3

118 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Overview of native dynamic SQL and DBMS_SQL –Introduction –Previous limitations Dynamic SQL support for CLOBs –Native dynamic SQL support for CLOBs – DBMS_SQL.PARSE() for CLOBs Converting between a REF CURSOR and a DBMS_SQL cursor – DBMS_SQL.TO_REF_CURSOR – DBMS_SQL.TO_CURSOR_NUMBER DBMS_SQL support for abstract data types

119 Copyright © 2007, Oracle. All rights reserved Transforming a DBMS_SQL Cursor into a REF CURSOR To add interoperability between native dynamic SQL and DBMS_SQL, you can transform a DBMS_SQL cursor into a PL/SQL REF CURSOR and vice versa. Two new functions are added into the DBMS_SQL package to support this feature: – DBMS_SQL.TO_REFCURSOR (cursor_number IN INTEGER) RETURN SYS_REFCURSOR; – DBMS_SQL.TO_CURSOR_NUMBER (rc IN OUT SYS_REFCURSOR) RETURN INTEGER;

120 Copyright © 2007, Oracle. All rights reserved Transforming a DBMS_SQL Cursor into a REF CURSOR : Example CREATE OR REPLACE PROCEDURE do_query (rep_id NUMBER) IS TYPE num_list IS TABLE OF NUMBER INDEX BY BINARY_INTEGER; TYPE cur_type IS REF CURSOR; src_cur cur_type; c_hndl NUMBER; cust_nos num_list; crdt_nos num_list; ret INTEGER; sql_stmt CLOB; BEGIN c_hndl := DBMS_SQL.OPEN_CURSOR; sql_stmt := 'SELECT customer_id, credit_limit FROM customers WHERE account_mgr_id = :b1'; DBMS_SQL.PARSE(c_hndl, sql_stmt, DBMS_SQL.NATIVE); DBMS_SQL.BIND_VARIABLE(c_hndl, 'b1', rep_id); ret := DBMS_SQL.EXECUTE(c_hndl); -- continued on next page

121 Copyright © 2007, Oracle. All rights reserved Transforming a DBMS_SQL Cursor into a REF CURSOR : Example -- continued from previous page -- switch from dbms_sql to native dynamic SQL src_cur := DBMS_SQL.TO_REFCURSOR(c_hndl); -- fetch with native dynamic SQL FETCH src_cur BULK COLLECT INTO cust_nos, crdt_nos; IF cust_nos.COUNT > 0 THEN DBMS_OUTPUT.PUT_LINE ('Customer Credit Limit'); DBMS_OUTPUT.PUT_LINE (' '); FOR i IN 1.. cust_nos.COUNT LOOP DBMS_OUTPUT.PUT_LINE(cust_nos(i) || ' ' || crdt_nos(i)); END LOOP; END IF; CLOSE src_cur; END do_query; /

122 Copyright © 2007, Oracle. All rights reserved Transforming a DBMS_SQL Cursor into a REF CURSOR : Example EXECUTE do_query(145) Customer Credit Limit PL/SQL procedure successfully completed.

123 Copyright © 2007, Oracle. All rights reserved Transforming a REF CURSOR into a DBMS_SQL Cursor: Example CREATE OR REPLACE PROCEDURE do_query2 (sql_stmt VARCHAR2, rep_id NUMBER) IS TYPE cur_type IS REF CURSOR; src_cur cur_type; c_hndl NUMBER; desctab DBMS_SQL.DESC_TAB; colcnt NUMBER; custid NUMBER; crdvar NUMBER; BEGIN OPEN src_cur FOR sql_stmt USING rep_id; -- switch from native dynamic SQL to DBMS_SQL: c_hndl := DBMS_SQL.TO_CURSOR_NUMBER(src_cur); DBMS_SQL.DESCRIBE_COLUMNS(c_hndl, colcnt, desctab); -- define columns FOR i in 1.. colcnt LOOP IF desctab(i).col_type=1 THEN DBMS_SQL.DEFINE_COLUMN(c_hndl, i, custid); ELSIF desctab(i).col_type = 2 THEN DBMS_SQL.DEFINE_COLUMN(c_hndl, i, crdvar); END IF; END LOOP; -- continued on next page

124 Copyright © 2007, Oracle. All rights reserved Transforming a REF CURSOR into a DBMS_SQL Cursor: Example -- continued from previous page -- fetch rows WHILE DBMS_SQL.FETCH_ROWS(c_hndl) > 0 LOOP FOR i IN 1.. colcnt LOOP IF desctab(i).col_type=1 THEN DBMS_SQL.COLUMN_VALUE(c_hndl, i, custid); ELSIF desctab(i).col_type = 2 THEN DBMS_SQL.COLUMN_VALUE(c_hndl, i, crdvar); END IF; END LOOP; -- could do more processing... END LOOP; DBMS_SQL.CLOSE_CURSOR(c_hndl); END do_query2; / EXECUTE do_query2('SELECT customer_id, credit_limit FROM customers - WHERE account_mgr_id = :b1', 148) PL/SQL procedure successfully completed.

125 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Overview of native dynamic SQL and DBMS_SQL –Introduction –Previous limitations Dynamic SQL support for CLOBs –Native dynamic SQL support for CLOBs – DBMS_SQL.PARSE() for CLOBs Converting between a REF CURSOR and a DBMS_SQL cursor – DBMS_SQL.TO_REF_CURSOR – DBMS_SQL.TO_CURSOR_NUMBER DBMS_SQL support for abstract data types

126 Copyright © 2007, Oracle. All rights reserved DBMS_SQL Support for Abstract Data Types (ADTs) Now allows: Collections –Varrays –Nested tables REFs Opaque types

127 Copyright © 2007, Oracle. All rights reserved DBMS_SQL Support for ADTs: Example CREATE OR REPLACE PROCEDURE update_phone_nos (p_new_nos phone_list_typ, p_cust_id customers.customer_id%TYPE) IS some_phone_nos phone_list_typ; c_hndl NUMBER; r NUMBER; sql_stmt CLOB := 'UPDATE customers SET phone_numbers = :b1 WHERE customer_id = :b2 RETURNING phone_numbers INTO :b3'; BEGIN c_hndl := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(c_hndl, sql_stmt, dbms_sql.native); DBMS_SQL.BIND_VARIABLE (c_hndl, 'b1', p_new_nos); DBMS_SQL.BIND_VARIABLE (c_hndl, 'b2', p_cust_id); DBMS_SQL.BIND_VARIABLE (c_hndl, 'b3', some_phone_nos); r := DBMS_SQL.EXECUTE (c_hndl); DBMS_SQL.VARIABLE_VALUE(c_hndl, 'b3', some_phone_nos); DBMS_SQL.CLOSE_CURSOR(c_hndl); -- continued on next page

128 Copyright © 2007, Oracle. All rights reserved DBMS_SQL Support for ADTs: Example -- continued from previous page -- select the phones nos sql_stmt := 'SELECT phone_numbers FROM customers WHERE customer_id = :b2'; c_hndl := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(c_hndl, sql_stmt, dbms_sql.native); DBMS_SQL.DEFINE_COLUMN(c_hndl, 1, some_phone_nos); DBMS_SQL.BIND_VARIABLE(c_hndl, 'b2', p_cust_id); r := DBMS_SQL.EXECUTE_AND_FETCH(c_hndl); DBMS_SQL.COLUMN_VALUE(c_hndl, 1, some_phone_nos); DBMS_SQL.CLOSE_CURSOR(c_hndl); FOR i IN some_phone_nos.FIRST.. some_phone_nos.LAST LOOP DBMS_OUTPUT.PUT_LINE('Phone number = ' || some_phone_nos(i) || ' updated.'); END LOOP; END update_phone_nos; /

129 Copyright © 2007, Oracle. All rights reserved DBMS_SQL Support for ADTs: Example Execute the UPDATE_PHONE_NOS procedure: DECLARE new_phone_nos phone_list_typ; BEGIN new_phone_nos := phone_list_typ (' ', ' ', ' ', ' '); update_phone_nos(new_phone_nos, 980); END; / Phone number = updated. Phone number = updated. Phone number = updated. Phone number = updated. PL/SQL successfully completed.

130 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to use the Oracle Database 11g enhancements to dynamic SQL: Write PL/SQL code that uses dynamic SQL and allows for SQL statements larger than 32 KB Convert a REF CURSOR to a DBMS_SQL cursor and vice versa to support interoperability Program using the enhancements to DBMS_SQL that include supporting collections and object types Create user-defined collection types and bulk-bind them using DBMS_SQL

131 Copyright © 2007, Oracle. All rights reserved Practice 4 Overview: Using the New Dynamic SQL Enhancements This practice covers the following topics: Writing code that uses both DBMS_SQL.PARSE and native dynamic SQL to accept SQL statements larger than 32 KB. Using DBMS_SQL with abstract data types and perform bulk binding with them.

132 Copyright © 2007, Oracle. All rights reserved Notes Page Only

133 Copyright © 2007, Oracle. All rights reserved Notes Page Only

134 Copyright © 2007, Oracle. All rights reserved Notes Page Only

135 5 Copyright © 2007, Oracle. All rights reserved. Implementing the Performance Improvements

136 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: List the compiler changes and explain how the changes impact native compilation Use the new SIMPLE_INTEGER data type Describe the process of inlining Use caching for optimization Use flashback to store and track all transactional changes to a record

137 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Compiler changes and how the changes impact native compilation The SIMPLE_INTEGER data type Inlining Caching –SQL result cache –PL/SQL function result cache Flashback enhancements –To store and track all transactional changes to a record over its lifetime

138 Copyright © 2007, Oracle. All rights reserved Real Native Compilation The compiler translates PL/SQL source directly to the dynamic-link library (DLL) for the current hardware. The compiler does the linking and loading so that the file system directories are no longer needed. The PL/SQL native compilation works out of the box, without requiring a C compiler on a production box. The PLSQL_CODE_TYPE parameter is the on/off switch. And, real native compilation is faster than the C native compilation.

139 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Compiler changes and how the changes impact native compilation The SIMPLE_INTEGER data type Inlining Caching –SQL result cache –PL/SQL function result cache Flashback enhancements –To store and track all transactional changes to a record over its lifetime

140 Copyright © 2007, Oracle. All rights reserved SIMPLE_INTEGER Data Type Definition: –Is a predefined subtype –Has the range – –Does not include a null value –Is allowed anywhere in PL/SQL where the PLS_INTEGER data type is allowed Benefits: –Eliminates the overhead of overflow checking –Is estimated to be 2–10 times faster when compared with the PLS_INTEGER type with native PL/SQL compilation

141 Copyright © 2007, Oracle. All rights reserved SIMPLE_INTEGER Data Type: Example CREATE OR REPLACE PROCEDURE p IS t0 NUMBER :=0; t1 NUMBER :=0; $IF $$Simple $THEN SUBTYPE My_Integer_t IS SIMPLE_INTEGER; My_Integer_t_Name CONSTANT VARCHAR2(30) := 'SIMPLE_INTEGER'; $ELSE SUBTYPE My_Integer_t IS PLS_INTEGER; My_Integer_t_Name CONSTANT VARCHAR2(30) := 'PLS_INTEGER'; $END v00 My_Integer_t := 0; v01 My_Integer_t := 0; v02 My_Integer_t := 0; v03 My_Integer_t := 0; v04 My_Integer_t := 0; v05 My_Integer_t := 0; two CONSTANT My_Integer_t := 2; lmt CONSTANT My_Integer_t := ; -- continued on next page

142 Copyright © 2007, Oracle. All rights reserved SIMPLE_INTEGER Data Type: Example -- continued from previous page BEGIN t0 := DBMS_UTILITY.GET_CPU_TIME(); WHILE v01 < lmt LOOP v00 := v00 + Two; v01 := v01 + Two; v02 := v02 + Two; v03 := v03 + Two; v04 := v04 + Two; v05 := v05 + Two; END LOOP; IF v01 <> lmt OR v01 IS NULL THEN RAISE Program_Error; END IF; t1 := DBMS_UTILITY.GET_CPU_TIME(); DBMS_OUTPUT.PUT_LINE( RPAD(LOWER($$PLSQL_Code_Type), 15)|| RPAD(LOWER(My_Integer_t_Name), 15)|| TO_CHAR((t1-t0), '9999')||' centiseconds'); END p; /

143 Copyright © 2007, Oracle. All rights reserved SIMPLE_INTEGER Data Type: Example ALTER PROCEDURE p COMPILE PLSQL_Code_Type = NATIVE PLSQL_CCFlags = 'simple:true' REUSE SETTINGS; Procedure altered. EXECUTE p() native simple_integer 51 centiseconds PL/SQL procedure successfully completed. ALTER PROCEDURE p COMPILE PLSQL_Code_Type = native PLSQL_CCFlags = 'simple:false' REUSE SETTINGS; Procedure altered. EXECUTE p() native pls_integer 884 centiseconds PL/SQL procedure successfully completed

144 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Compiler changes and how the changes impact native compilation The SIMPLE_INTEGER data type Inlining Caching –SQL result cache –PL/SQL function result cache Flashback enhancements –To store and track all transactional changes to a record over its lifetime

145 Copyright © 2007, Oracle. All rights reserved Intra Unit Inlining Definition: –Inlining is defined as the replacement of a call to subroutine with a copy of the body of the subroutine that is called. –The copied procedure generally runs faster than the original. –The PL/SQL compiler can automatically find the calls that should be inlined. Benefits: –Inlining can provide large performance gains when applied judiciously by a factor of 2–10 times.

146 Copyright © 2007, Oracle. All rights reserved Use of Inlining Influence implementing inlining via two methods: –Oracle parameter PLSQL_OPTIMIZE_LEVEL – PRAGMA INLINE Recommend that you: –Inline small programs –Inline programs that are frequently executed Use performance tools to identify hot spots suitable for inline applications: – plstimer

147 Copyright © 2007, Oracle. All rights reserved Inlining Concepts Noninlined program: CREATE OR REPLACE PROCEDURE small_pgm IS a NUMBER; b NUMBER; PROCEDURE touch(x IN OUT NUMBER, y NUMBER) IS BEGIN IF y > 0 THEN x := x*x; END IF; END; BEGIN a := b; FOR I IN LOOP touch(a, -17); a := a*b; END LOOP; END small_pgm;

148 Copyright © 2007, Oracle. All rights reserved Inlining Concepts Examine the loop after inlining:... BEGIN a := b; FOR i IN LOOP IF –17 > 0 THEN a := a*a; END IF; a := a*b; END LOOP; END small_pgm;...

149 Copyright © 2007, Oracle. All rights reserved Inlining Concepts The loop is transformed in several steps: a := b; FOR i IN LOOP... IF false THEN a := a*a; END IF; a := a*b; END LOOP; a := b; FOR i IN LOOP... a := a*b; END LOOP; a := b; a := a*b; FOR i IN LOOP... END LOOP; a := b*b; FOR i IN LOOP... END LOOP;

150 Copyright © 2007, Oracle. All rights reserved Inlining: Example Set the PLSQL_OPTIMIZE_LEVEL session-level parameter to a value of 2 or 3: –Setting it to 2 means no automatic inlining is attempted. –Setting it to 3 means automatic inlining is attempted and no pragmas are necessary. Within a PL/SQL subroutine, use PRAGMA INLINE –NO means no inlining occurs regardless of the level and regardless of the YES pragmas. –YES means inline at level 2 of a particular call and increase the priority of inlining at level 3 for the call. ALTER PROCEDURE small_pgm COMPILE PLSQL_OPTIMIZE_LEVEL = 3 REUSE SETTINGS;

151 Copyright © 2007, Oracle. All rights reserved Inlining: Example After setting the PLSQL_OPTIMIZE_LEVEL parameter, use a pragma: CREATE OR REPLACE PROCEDURE small_pgm IS a PLS_INTEGER; FUNCTION add_it(a PLS_INTEGER, b PLS_INTEGER) RETURN PLS_INTEGER IS BEGIN RETURN a + b; END; BEGIN pragma INLINE (small_pgm, 'YES'); a := add_it(3, 4) + 6; END small_pgm;

152 Copyright © 2007, Oracle. All rights reserved Inlining: Guidelines Pragmas apply only to calls in the next statement following the pragma. Programs that make use of smaller helper subroutines are good candidates for inlining. Only local subroutines can be inlined. You cannot inline an external subroutine. Cursor functions should not be inlined. Inlining can increase the size of a unit. Be careful about suggesting to inline functions that are deterministic.

153 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Compiler changes and how the changes impact native compilation The SIMPLE_INTEGER data type Inlining Caching –SQL result cache –PL/SQL function result cache Flashback enhancements –To store and track all transactional changes to a record over its lifetime

154 Copyright © 2007, Oracle. All rights reserved SQL Query Result Cache Definition: –Cache the results of the current query or query fragment in memory and then use the cached results in future executions of the query or query fragments. –Cached results reside in the result cache memory portion of the SGA. Benefits: –Improved performance

155 Copyright © 2007, Oracle. All rights reserved SQL Query Result Cache Scenario: –You need to find the greatest average value of credit limit grouped by state over the whole population. –The query results in a huge number of rows analyzed to yield a few or one row. –In your query, the data changes fairly slowly (say every hour) but the query is repeated fairly often (say every second). Solution: –Use the new optimizer hint /*+ result_cache */ in your query: SELECT /*+ result_cache */ AVG(cust_credit_limit), cust_state_province FROM sh.customers GROUP BY cust_state_province;

156 Copyright © 2007, Oracle. All rights reserved PL/SQL Function Result Cache Definition: –Enables data that is stored in cache to be shared across sessions –Stores the function result cache in a shared global area (SGA), making it available to any session that runs your application Benefits: –Improved performance –Improved scalability

157 Copyright © 2007, Oracle. All rights reserved PL/SQL Function Result Cache Scenario: –You need a PL/SQL function that derives a complex metric. –The data that your function calculates changes slowly, but the function is frequently called. Solution: –Use the new result_cache clause in your function definition.

158 Copyright © 2007, Oracle. All rights reserved Enabling Result Caching Include the RESULT_CACHE option in the function definition. Optionally, include the RELIES_ON clause. CREATE OR REPLACE FUNCTION productName (prod_id NUMBER, lang_id VARCHAR2) RETURN NVARCHAR2 RESULT_CACHE RELIES_ON (product_descriptions) IS result VARCHAR2(50); BEGIN SELECT translated_name INTO result FROM product_descriptions WHERE product_id = prod_id AND language_id = lang_id; RETURN result; END;

159 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Compiler changes and how the changes impact native compilation The SIMPLE_INTEGER data type Inlining Caching –SQL result cache –PL/SQL function result cache Flashback enhancements –To store and track all transactional changes to a record over its lifetime

160 Copyright © 2007, Oracle. All rights reserved Flashback Data Archives Provide the ability to store and track all transactional changes to a record over its lifetime Save development resources because you no longer need to build this intelligence into your application Are useful for compliance with record stage policies and audit reports

161 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive Process 1.Create the Flashback Data Archive. 2.Specify the default Flashback Data Archive. 3.Enable the Flashback Data Archive. 4.View Flashback Data Archive data.

162 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive Scenario Using Flashback Data Archive to access historical data: CONNECT AS sysdba -- create the Flashback Data Archive CREATE FLASHBACK ARCHIVE DEFAULT fla1 TABLESPACE example QUOTA 10G RETENTION 5 YEAR; -- Enable Flashback Data Archive ALTER TABLE oe1.inventories FLASHBACK ARCHIVE; ALTER TABLE oe1.warehouses FLASHBACK ARCHIVE; -- Specify the default Flashback Data Archive ALTER FLASHBACK ARCHIVE fla1 SET DEFAULT; 1 2 3

163 Copyright © 2007, Oracle. All rights reserved

164 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive Scenario Using Flashback Data Archive to access historical data: Examine the data: Change the data: Examine the flashback data: SELECT product_id, warehouse_id, quantity_on_hand FROM oe1.inventories AS OF TIMESTAMP TO_TIMESTAMP (' :00:00', 'YYYY-MM-DD HH24:MI:SS') WHERE product_id = 3108; SELECT product_id, warehouse_id, quantity_on_hand FROM oe1.inventories WHERE product_id = 3108; UPDATE oe1.inventories SET quantity_on_hand = 300 WHERE product_id = 3108; 1 2 3

165 Copyright © 2007, Oracle. All rights reserved

166 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive Dictionary Views Viewing the results: View NameDescription *_FLASHBACK_ARCHIVE Displays information about Flashback Data Archives *_FLASHBACK_ARCHIVE_TS Displays tablespaces of Flashback Data Archives *_FLASHBACK_ARCHIVE_TABLES Displays information about tables that are enabled for flashback archiving

167 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive Dictionary Views Viewing information about tables that are enabled for flashback archiving: DESCRIBE dba_flashback_archive_tables Name Null? Type TABLE_NAME NOT NULL VARCHAR2(30) OWNER_NAME NOT NULL VARCHAR2(30) FLASHBACK_ARCHIVE_NAME NOT NULL VARCHAR2(255) ARCHIVE_TABLE_NAME VARCHAR2(53) SELECT * FROM dba_flashback_archive_tables; TABLE_NAME OWNER_NAME FLASHBACK_ARCHIVE_NAME ARCHIVE_TABLE_NAME INVENTORIES OE FLA1 SYS_FBA_HIST_70355 WAREHOUSES OE FLA1 SYS_FBA_HIST_70336

168 Copyright © 2007, Oracle. All rights reserved Flashback Data Archive DDL Restrictions Using any of the following DDL statements on a table enabled for Flashback Data Archive causes the error ORA-55610: Invalid DDL statement on history-tracked table ALTER TABLE statement that does any of the following: –Drops, renames, or modifies a column –Performs partition or subpartition operations –Converts a LONG column to a LOB column –Includes an UPGRADE TABLE clause, with or without an INCLUDING DATA clause DROP TABLE statement RENAME TABLE statement TRUNCATE TABLE statement

169 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: List the compiler changes and explain how the changes impact native compilation Use the new SIMPLE_INTEGER data type Describe the process of inlining Use caching for optimization Use flashback to store and track all transactional changes to a record

170 Copyright © 2007, Oracle. All rights reserved Practice 5 Overview: Implementing Performance Improvements This practice covers the following topics: Testing the performance of the SIMPLE_INTEGER data type Writing code to use SQL caching Writing code to use PL/SQL caching Examining inlined code and practicing how to influence inlining

171 Copyright © 2007, Oracle. All rights reserved Notes Page Only

172 Copyright © 2007, Oracle. All rights reserved Notes Page Only

173 Copyright © 2007, Oracle. All rights reserved Notes Page Only

174 Copyright © 2007, Oracle. All rights reserved Notes Page Only

175 Copyright © 2007, Oracle. All rights reserved Notes Page Only

176 Copyright © 2007, Oracle. All rights reserved Notes Page Only

177 6 Copyright © 2007, Oracle. All rights reserved. Practicing the Language Usability Enhancements

178 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Implement the sequence calls to NEXTVAL and CURRVAL without using a SQL statement to retrieve the values Use the new CONTINUE statement to control the next loop iteration or to leave a loop Use both named and mixed notation calls to functions from a SQL statement Use the ALTER TABLE statement to change tables to read- only status

179 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Changes to sequence calls The new CONTINUE statement Named and mixed notation calls Read-only tables

180 Copyright © 2007, Oracle. All rights reserved Sequence Enhancement in PL/SQL Expressions Prior to Oracle Database 11g release: References to sequences were permitted only through SQL statements Use of CURRVAL and NEXTVAL pseudocolumns was not allowed in PL/SQL unless embedded in a SQL statement Using sequences in PL/SQL was cumbersome and required an additional SQL statement in a PL/SQL subroutine

181 Copyright © 2007, Oracle. All rights reserved Sequence Enhancement in PL/SQL Expressions Enhancements in Oracle Database 11g: You can use the CURRVAL and NEXTVAL pseudocolumns, qualified by a sequence name, directly in a PL/SQL expression. Sequence usability is improved. Less typing is required by the developer. The resulting code is clearer

182 Copyright © 2007, Oracle. All rights reserved Using Sequences in PL/SQL Expressions Pre-Oracle Database 11g: Starting in Oracle Database 11g: declare v_new_id NUMBER; BEGIN SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual; END; / DECLARE v_new_id NUMBER; BEGIN v_new_id := my_seq.NEXTVAL; END; /

183 Copyright © 2007, Oracle. All rights reserved Using Sequences in PL/SQL Expressions Try to avoid using the old syntax anymore: SELECT my_seq.NEXTVAL INTO v_new_id FROM dual;

184 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Changes to sequence calls The new CONTINUE statement Named and mixed notation calls Read-only tables

185 Copyright © 2007, Oracle. All rights reserved PL/SQL CONTINUE Statement Definition: –Adds the functionality to begin the next loop iteration –Provides programmers with the ability to transfer control to the next iteration of a loop –Uses parallel structure and semantics to the EXIT statement Benefits: –Eases the programming process –May see a small performance improvement over the previous programming workarounds to simulate the CONTINUE statement

186 Copyright © 2007, Oracle. All rights reserved PL/SQL CONTINUE Statement: Usage Offers you a simplified means to control loop iterations Can be more efficient than previous coding workarounds Is commonly used to filter data inside a loop body before the main processing begins

187 Copyright © 2007, Oracle. All rights reserved PL/SQL CONTINUE Statement: Example DECLARE v_total SIMPLE_INTEGER := 0; BEGIN FOR i IN LOOP v_total := v_total + i; dbms_output.put_line ('Total is: '|| v_total); CONTINUE WHEN i > 5; v_total := v_total + i; dbms_output.put_line ('End of Loop Total is: '|| v_total); END LOOP; END; / 1 2 Total is: 1 End of Loop Total is: 2 Total is: 4 End of Loop Total is: 6 Total is: 9 End of Loop Total is: 12 Total is: 16 End of Loop Total is: 20 Total is: 25 End of Loop Total is: 30 Total is: 36 Total is: 43 Total is: 51 Total is: 60 Total is: 70 PL/SQL procedure successfully completed.

188 Copyright © 2007, Oracle. All rights reserved PL/SQL CONTINUE Statement: Example CREATE OR REPLACE PROCEDURE two_loop IS v_total NUMBER := 0; BEGIN > FOR i IN LOOP v_total := v_total + 1; dbms_output.put_line ('Total is: ' || v_total); FOR j IN LOOP CONTINUE BeforeTopLoop WHEN i + j > 5; v_total := v_total + 1; END LOOP; END two_loop; Procedure created. --RESULTS: EXECUTE two_loop Total is: 1 Total is: 6 Total is: 10 Total is: 13 Total is: 15 Total is: 16 Total is: 17 Total is: 18 Total is: 19 Total is: 20 PL/SQL procedure successfully completed.

189 Copyright © 2007, Oracle. All rights reserved CONTINUE Statement: Guidelines The CONTINUE statement offers you the functionality to transfer control within a loop back to a new iteration or to leave the loop. The CONTINUE statement cannot appear outside a loop at all; this generates a compiler error. You cannot use the CONTINUE statement to pass through a procedure, function, or method boundary; this generates a compiler error.

190 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Changes to sequence calls The new CONTINUE statement Named and mixed notation calls Read-only tables

191 Copyright © 2007, Oracle. All rights reserved Named and Mixed Notation from SQL Definition: –PL/SQL allows arguments in a subroutine call to be specified using positional, named, or mixed notation. –Before Oracle Database 11g, only the positional notation was supported in calls from SQL. –Starting in Oracle Database 11g, named and mixed notation can be used for specifying arguments in calls to PL/SQL subroutines from SQL statements. Benefits: –For long parameter lists, with most having default values, you can omit values from the optional parameters. –You can avoid duplicating the default value of the optional parameter at each call site.

192 Copyright © 2007, Oracle. All rights reserved Named and Mixed Notation from SQL: Example CREATE OR REPLACE FUNCTION f ( p1 IN NUMBER DEFAULT 1, p5 IN NUMBER DEFAULT 5) RETURN NUMBER IS v number; BEGIN v:= p1 + (p5 * 2); RETURN v; END f; / Function created. SELECT f(p5 => 10) FROM DUAL; F(P5=>10)

193 Copyright © 2007, Oracle. All rights reserved Lesson Agenda Changes to sequence calls The new CONTINUE statement Named and mixed notation calls Read-only tables

194 Copyright © 2007, Oracle. All rights reserved Read-Only Tables Use the ALTER TABLE syntax to put a table into read-only mode: Prevents DDL or DML changes during table maintenance Changes it back into read/write mode ALTER TABLE customers READ ONLY; -- perform table maintenance and then -- return table back to read/write mode ALTER TABLE customers READ WRITE;

195 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Implement the sequence calls to NEXTVAL and CURRVAL without using a SQL statement to retrieve the values. Use the new CONTINUE statement to control the next loop iteration or to leave a loop. Use both named and mixed notation calls to functions from a SQL statement. Use the ALTER TABLE statement to change tables to read- only status.

196 Copyright © 2007, Oracle. All rights reserved Practice 6 Overview: Using the New SQL and PL/SQL Usability Features This practice covers the following topics: Trying the new syntax for sequences Controlling loop iteration with the CONTINUE statement Using the named and mixed notation calls to functions from a SQL statement Changing the status of a table to read-only

197 Copyright © 2007, Oracle. All rights reserved Notes Page Only

198 Copyright © 2007, Oracle. All rights reserved Notes Page Only

199 Copyright © 2007, Oracle. All rights reserved Notes Page Only

200 Copyright © 2007, Oracle. All rights reserved Notes Page Only

201 7 Copyright © 2007, Oracle. All rights reserved. Developing Triggers that Utilize the New Enhancements

202 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Describe compound triggers Create compound triggers Create disabled triggers Use the ENABLE clause with a trigger Control trigger order with the FOLLOWS clause

203 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Overview Definition: –It is a single trigger on a table that allows you to specify actions for each of four timing points of the trigger. –The trigger body supports a common PL/SQL state that the code for each timing point can access. –You can avoid the mutating table error by allowing rows destined for a second table to accumulate and then bulk- inserting them. Benefits: –Improved usability for the PL/SQL programmer –Improved run-time performance and scalability

204 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Overview Can be used on tables or views A single trigger with four timing points: 1.Before the firing statement 2.Before each row that the firing statement affects 3.After each row that the firing statement affects 4.After the firing statement INSERT UPDATE DELETE Before statement Before row After row After statement

205 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Structure For tables: CREATE OR REPLACE TRIGGER schema.trigger FOR dml_event_clause ON schema.table COMPOUND TRIGGER -- Initial section -- Declarations -- Subprograms -- Optional section BEFORE STATEMENT IS...; -- Optional section BEFORE EACH ROW IS...; -- Optional section AFTER EACH ROW IS...; -- Optional section AFTER STATEMENT IS...; 1 2

206 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Structure For views: CREATE OR REPLACE TRIGGER schema.trigger FOR dml_event_clause ON schema.view COMPOUND TRIGGER -- Initial section -- Declarations -- Subprograms -- Optional section (exclusive) INSTEAD OF EACH ROW IS...;

207 Copyright © 2007, Oracle. All rights reserved

208 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Scenario Track changes on the ORDER_TOTAL column in the ORDERS table to an audit table: INSERT UPDATE ORDERS table ORDERTOTALS_AUDIT table

209 Copyright © 2007, Oracle. All rights reserved Supporting Structures for Compound Trigger: Example CREATE SEQUENCE ordertotals_audit_seq START WITH 2500; CREATE OR REPLACE TRIGGER gen_ordertotals_audit_id_trg BEFORE INSERT ON orders FOR EACH ROW BEGIN :NEW.order_id := ordertotals_audit_seq.NEXTVAL; END gen_ordertotals_audit_id_trg; CREATE TABLE ordertotals_audit( order_id NUMBER NOT NULL, change_date DATE NOT NULL, user_id VARCHAR2(30), old_total NUMBER(8, 2) NOT NULL, new_total NUMBER(8, 2) NOT NULL, CONSTRAINT order_total_PK PRIMARY KEY (order_id, change_date), CONSTRAINT orders_FK FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE);

210 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Example CREATE OR REPLACE TRIGGER maintain_ordertotals_audit_trg FOR INSERT OR UPDATE OF order_total ON orders COMPOUND TRIGGER --Initial section begins --Declarations threshhold CONSTANT SIMPLE_INTEGER := 7; TYPE order_totals_t IS TABLE OF ordertotals_audit%rowtype INDEX BY PLS_INTEGER; o_totals order_totals_t; idx SIMPLE_INTEGER := 0; -- subprogram PROCEDURE Flush_Array IS n CONSTANT SIMPLE_INTEGER := o_totals.Count(); BEGIN FORALL j IN 1..n INSERT INTO ordertotals_audit VALUES o_totals(j); o_totals.Delete(); idx := 0; DBMS_Output.Put_Line('Flushed '||n||' rows'); END Flush_Array; -- Initial section ends

211 Copyright © 2007, Oracle. All rights reserved Compound Trigger: Example -- Optional section BEFORE STATEMENT IS BEGIN o_totals.Delete(); idx := 0; END BEFORE STATEMENT; AFTER EACH ROW IS BEGIN idx := idx + 1; o_totals(idx).order_ID := :New.order_ID; o_totals(idx).Change_Date := SYSDATE(); o_totals(idx).user_id := sys_context('userenv', 'session_user'); o_totals(idx).old_total := :OLD.order_total; o_totals(idx).new_total := :NEW.order_total; IF idx >= Threshhold THEN -- PLW-06005: inlining... done Flush_Array(); END IF; END AFTER EACH ROW; AFTER STATEMENT IS BEGIN -- PLW-06005: inlining... done Flush_Array(); END AFTER STATEMENT; END maintain_ordertotals_audit_trg;

212 Copyright © 2007, Oracle. All rights reserved Compiling the Compound Trigger The session settings are enabled for inlining and viewing all compiler messages. The warning message tells you that inlining is performed. The trigger is successfully compiled; this is only an informational warning.

213 Copyright © 2007, Oracle. All rights reserved Firing the Compound Trigger Execute a statement to force the trigger to fire: Examine the results in the audit table: SELECT * FROM ordertotals_audit; ORDER_ID CHANGE_DATE USER_ID OLD_TOTAL NEW_TOTAL JUL-07 OE JUL-07 OE JUL-07 OE JUL-07 OE JUL-07 OE JUL-07 OE UPDATE orders SET order_total = order_total * 1.05 WHERE order_status = 10; 1

214 Copyright © 2007, Oracle. All rights reserved Other Trigger Changes More control over triggers CREATE TRIGGER now includes the ENABLE, DISABLE, and FOLLOWS clauses that give you more control over triggers. –The DISABLE clause lets you create a trigger in a disabled state so that you can ensure that your code compiles successfully before you enable the trigger. –The ENABLE clause enables the trigger. –The FOLLOWS clause allows you to specify that the trigger you are creating fires after certain other triggers.

215 Copyright © 2007, Oracle. All rights reserved Creating a Disabled Trigger Prior to Oracle Database 11g, if you created a trigger whose body has a PL/SQL compilation error, DML to the table fails with ORA-04098: trigger 'TRG' is invalid and failed re-validation. It is safer to create it as disabled, and then, to enable it only when you know it will be compiled without an error. CREATE OR REPLACE TRIGGER gen_cust_id BEFORE INSERT ON customers FOR EACH ROW DISABLE BEGIN :NEW.customer_id := customer_seq.Nextval; END; /

216 Copyright © 2007, Oracle. All rights reserved FOLLOWS Clause To ensure that a trigger fires after certain other triggers defined on the same object, use the FOLLOWS clause when you create the first trigger. Trig1Trig2Trig3Trig4 FOLLOWS

217 Copyright © 2007, Oracle. All rights reserved FOLLOWS Clause Applies to both compound and simple triggers Lets you order the executions of multiple triggers relative to each other Can be placed: –In the definition of a simple trigger with a compound trigger target –In the definition of a compound trigger with a simple trigger target Applies only to the section of the compound trigger with the same timing point as the simple trigger: –If the compound trigger has no such timing point, FOLLOWS is quietly ignored.

218 Copyright © 2007, Oracle. All rights reserved FOLLOWS Clause: Scenario CREATE OR REPLACE TRIGGER change_product AFTER UPDATE of product_id ON order_items FOR EACH ROW FOLLOWS oe1.compute_total BEGIN dbms_output.put_line ('Do processing here … '); END; COMPUTE_TOTALCHANGE_PRODUCT FOLLOWS

219 Copyright © 2007, Oracle. All rights reserved FOLLOWS Clause: Example CREATE OR REPLACE TRIGGER compute_total AFTER UPDATE OR INSERT OR DELETE of unit_price, quantity ON order_items FOR EACH ROW BEGIN IF UPDATING THEN UPDATE orders SET order_total = order_total – (:old.unit_price * :old.quantity) + (:new.quantity * :new.unit_price) WHERE order_id = :old.order_id; ELSIF DELETING THEN UPDATE orders SET order_total = order_total – (:old.unit_price * :old.quantity) WHERE order_id = :old.order_id; ELSE --inserting UPDATE orders SET order_total = order_total + (:new.quantity * :new.unit_price) WHERE order_id = :old.order_id; END IF; END;

220 Copyright © 2007, Oracle. All rights reserved FOLLOWS Clause: Example UPDATE order_items SET product_id=3165 WHERE order_id = 2412 AND line_item_id = 8; Do processing here... 1 row updated. SELECT order_id, order_date, customer_id, order_status, order_total FROM orders WHERE customer_id = 170; ORDER_ID ORDER_DAT CUSTOMER_ID ORDER_STATUS ORDER_TOTAL MAR UPDATE order_items SET quantity = 100 WHERE order_id = 2412 AND line_item_id = 9; 1 row updated

221 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Describe compound triggers Create compound triggers Create disabled triggers Use the ENABLE clause with a trigger Control trigger order with the FOLLOWS clause

222 Copyright © 2007, Oracle. All rights reserved Practice 7 Overview: Using the New Trigger Enhancements This practice covers the following topics: Creating a disabled trigger and then enabling it Writing a compound trigger Controlling the trigger firing order with the new FOLLOWS clause

223 Copyright © 2007, Oracle. All rights reserved Notes Page Only

224 Copyright © 2007, Oracle. All rights reserved Notes Page Only

225 Copyright © 2007, Oracle. All rights reserved Notes Page Only

226 Copyright © 2007, Oracle. All rights reserved Notes Page Only

227 8 Copyright © 2007, Oracle. All rights reserved. Implementing SecureFile LOBs

228 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Describe SecureFile LOB features Enable SecureFile LOB deduplication, compression, and encryption Migrate BasicFile LOBs to the SecureFile LOB format Analyze the performance of LOBs

229 Copyright © 2007, Oracle. All rights reserved Lesson Agenda SecureFile LOB features Deduplication, compression, and encryption Migration of BasicFile LOBs to the SecureFile LOB format Performance of LOBs

230 Copyright © 2007, Oracle. All rights reserved Introducing SecureFile LOBs Oracle Database 11g offers a reengineered large object (LOB) data type that: Improves performance Eases manageability Simplifies application development Offers advanced, next-generation functionality such as intelligent compression and transparent encryption

231 Copyright © 2007, Oracle. All rights reserved Storage of SecureFile LOBs Oracle Database 11g implements a new storage paradigm for LOB storage: If the SECUREFILE storage keyword appears in the CREATE TABLE statement, the new storage is used. If the BASICFILE storage keyword appears in the CREATE TABLE statement, the old storage paradigm is used. By default, the storage is BASICFILE, unless you modify the setting for the DB_SECUREFILE parameter in the init.ora file.

232 Copyright © 2007, Oracle. All rights reserved Setting Up SecureFile LOBs Create a tablespace for the LOB data: Create a table to hold the LOB data: CONNECT CREATE TABLE customer_profiles (id NUMBER, first_name VARCHAR2 (40), last_name VARCHAR2 (80), profile_info BLOB) LOB(profile_info) STORE AS SECUREFILE (TABLESPACE sf_tbs1); -- have your dba do this: CREATE TABLESPACE sf_tbs1 DATAFILE 'sf_tbs1.dbf' SIZE 1500M REUSE AUTOEXTEND ON NEXT 200M MAXSIZE 3000M SEGMENT SPACE MANAGEMENT AUTO; 1 2

233 Copyright © 2007, Oracle. All rights reserved Writing Data to the SecureFile LOB Create the procedure to read the MS Word files and load them into the LOB column. Call this procedure from the WRITE_LOB procedure (shown on the next page). CREATE OR REPLACE PROCEDURE loadLOBFromBFILE_proc (dest_loc IN OUT BLOB, file_name IN VARCHAR2) IS src_loc BFILE := BFILENAME('CWD', file_name); amount INTEGER := 4000; BEGIN DBMS_LOB.OPEN(src_loc, DBMS_LOB.LOB_READONLY); amount := DBMS_LOB.GETLENGTH(src_loc); DBMS_LOB.LOADFROMFILE(dest_loc, src_loc, amount); DBMS_LOB.CLOSE(src_loc); END loadLOBFromBFILE_proc;

234 Copyright © 2007, Oracle. All rights reserved Writing Data to the SecureFile LOB Create the procedure to insert LOBs into the table: CREATE OR REPLACE PROCEDURE write_lob (p_file IN VARCHAR2) IS i NUMBER; v_fn VARCHAR2(15); v_ln VARCHAR2(40); v_b BLOB; BEGIN DBMS_OUTPUT.ENABLE; DBMS_OUTPUT.PUT_LINE('Begin inserting rows...'); FOR i IN LOOP v_fn:=SUBSTR(p_file,1,INSTR(p_file,'.')-1); v_ln:=SUBSTR(p_file,INSTR(p_file,'.')+1,LENGTH(p_file)- INSTR(p_file,'.')-4); INSERT INTO customer_profiles VALUES i, v_fn, v_ln, EMPTY_BLOB()) RETURNING profile_info INTO v_b; loadLOBFromBFILE_proc(v_b,p_file); DBMS_OUTPUT.PUT_LINE('Row '|| i ||' inserted.'); END LOOP; COMMIT; END write_lob;

235 Copyright © 2007, Oracle. All rights reserved Writing Data to the SecureFile LOB set serveroutput on set verify on set term on set linesize 200 timing start load_data execute write_lob('karl.brimmer.doc'); execute write_lob('monica.petera.doc'); execute write_lob('david.sloan.doc'); timing stop 1 2

236 Copyright © 2007, Oracle. All rights reserved Important Instructions

237 Copyright © 2007, Oracle. All rights reserved Reading LOBs from the Table Create the procedure to read LOBs from the table: CREATE OR REPLACE PROCEDURE read_lob IS lob_loc BLOB; CURSOR profiles_cur IS SELECT id, first_name, last_name, profile_info FROM customer_profiles; profiles_rec customer_profiles%ROWTYPE; BEGIN OPEN profiles_cur; LOOP FETCH profiles_cur INTO profiles_rec; lob_loc := profiles_rec.profile_info; DBMS_OUTPUT.PUT_LINE('The length is: '|| DBMS_LOB.GETLENGTH(lob_loc)); DBMS_OUTPUT.PUT_LINE('The ID is: '|| profiles_rec.id); DBMS_OUTPUT.PUT_LINE('The blob is read: '|| UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(lob_loc,200,1))); EXIT WHEN profiles_cur%NOTFOUND; END LOOP; CLOSE profiles_cur; END;

238 Copyright © 2007, Oracle. All rights reserved Important Instructions

239 Copyright © 2007, Oracle. All rights reserved Lesson Agenda SecureFile LOB features Deduplication, compression, and encryption Migration of BasicFile LOBs to the SecureFile LOB format Performance of LOBs

240 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression To enable deduplication and compression, use the ALTER TABLE statement with the DEDUPLICATE and COMPRESS options. By enabling deduplication with SecureFiles, duplicate LOB data is automatically detected and space is conserved by storing only one copy. Enabling compression turns on LOB compression. ALTER TABLE tblname MODIFY LOB lobcolname (DEDUPLICATE option COMPRESS option)

241 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example 1.Check the space being used by the CUSTOMER_PROFILES table. 2.Enable deduplication and compression on the PROFILE_INFO LOB column with the ALTER TABLE statement. 3.Recheck the space being used by the CUSTOMER_PROFILES table. 4.Reclaim the space.

242 Copyright © 2007, Oracle. All rights reserved Important Instructions

243 Copyright © 2007, Oracle. All rights reserved Important Instructions

244 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example Checking LOB space usage: execute check_space anonymous block completed FS1 Blocks = 0 Bytes = 0 FS2 Blocks = 1 Bytes = 8192 FS3 Blocks = 0 Bytes = 0 FS4 Blocks = 4 Bytes = Full Blocks = 0 Bytes = 0 ============================================= Total Blocks = 5 || Total Bytes = 40960

245 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example Enabling deduplication and compression: ALTER TABLE customer_profiles MODIFY LOB (profile_info) (DEDUPLICATE LOB COMPRESS HIGH); Table altered.

246 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example Rechecking LOB space usage: execute check_space anonymous block completed FS1 Blocks = 0 Bytes = 0 FS2 Blocks = 1 Bytes = 8192 FS3 Blocks = 0 Bytes = 0 FS4 Blocks = 4 Bytes = Full Blocks = 0 Bytes = 0 ============================================= Total Blocks = 5 || Total Bytes = 40960

247 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example Reclaiming the free space: ALTER TABLE customer_profiles ENABLE ROW MOVEMENT; Table altered. ALTER TABLE customer_profiles SHRINK SPACE COMPACT; Table altered. ALTER TABLE customer_profiles SHRINK SPACE; Table altered

248 Copyright © 2007, Oracle. All rights reserved Enabling Deduplication and Compression: Example Examining the space after reclaiming: execute check_space anonymous block completed FS1 Blocks = 0 Bytes = 0 FS2 Blocks = 1 Bytes = 8192 FS3 Blocks = 0 Bytes = 0 FS4 Blocks = 0 Bytes = 0 Full Blocks = 0 Bytes = 8192 ============================================= Total Blocks = 1 || Total Bytes = 16384

249 Copyright © 2007, Oracle. All rights reserved Encryption The encryption option enables you to turn on or off the LOB encryption, and optionally select an encryption algorithm. Encryption is performed at the block level. You can specify the encryption algorithm: – 3DES168 – AES128 – AES192 (default) – AES256 The column encryption key is derived from PASSWORD. All LOBs in the LOB column will be encrypted. DECRYPT keeps the LOBs in cleartext. LOBs can be encrypted on a per-column or per-partition basis.

250 Copyright © 2007, Oracle. All rights reserved Using Encryption You need a directory to store the Transparent Data Encryption (TDE) wallet. This is required for the SecureFiles LOB encryption. Edit the $ORACLE_HOME/network/admin/sqlnet.ora file to indicate the location of the TDE wallet. mkdir $ORACLE_HOME/wallet ENCRYPTION_WALLET_LOCATION= (SOURCE=(METHOD=FILE)(METHOD_DATA= (DIRECTORY =/u01/app/oracle/product/11.1.0/db_1/wallet)))

251 Copyright © 2007, Oracle. All rights reserved Using Encryption: Example Enabling encryption: Verify that the LOB is encrypted: ALTER TABLE customer_profiles MODIFY (profile_info ENCRYPT USING 'AES192'); Table altered. SELECT * FROM user_encrypted_columns; TABLE_NAME COLUMN_NAME ENCRYPTION_ALG SAL CUSTOMER_PROFILES PROFILE_INFO AES 192 bits key YES

252 Copyright © 2007, Oracle. All rights reserved Lesson Agenda SecureFile LOB features Deduplication, compression, and encryption Migration of BasicFile LOBs to the SecureFile LOB format Performance of LOBs

253 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format Scenario: You have data that is stored in the BasicFile format. You want to migrate it to the SecureFile format. connect CREATE TABLE customer_profiles (id NUMBER, first_name VARCHAR2 (40), last_name VARCHAR2 (80), profile_info BLOB) LOB(profile_info) STORE AS BASICFILE (TABLESPACE bf_tbs1); connect CREATE TABLESPACE bf_tbs1 DATAFILE 'bf_tbs1.dbf' SIZE 800M REUSE EXTENT MANAGEMENT LOCAL UNIFORM SIZE 64M SEGMENT SPACE MANAGEMENT AUTO;

254 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format Load the data to the BasicFile LOB: set serveroutput on set verify on set term on set linesize 200 timing start load_data execute write_lob('karl.brimmer.doc'); execute write_lob('monica.petera.doc'); execute write_lob('david.sloan.doc'); timing stop PL/SQL procedure successfully completed. timing for: load_data Elapsed: 00:00:01.68

255 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format Check the timing on reading data in BasicFile format: set serveroutput on set verify on set term on set lines 200 timing start read_data execute read_lob; timing stop PL/SQL procedure successfully completed. timing for: read_data Elapsed: 00:00:01.15

256 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format Check the LOB segment subtype name for BasicFile format: col segment_name format a30 col segment_type format 13 SELECT segment_name, segment_type, segment_subtype FROM dba_segments WHERE tablespace_name = 'BF_TBS1' AND segment_type = 'LOBSEGMENT'; SEGMENT_NAME SEGMENT_TYPE SEGME SYS_LOB C00004$$ LOBSEGMENT ASSM

257 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format The migration from BasicFile to SecureFiles LOB storage format is performed online. This means that the CUSTOMERS_PROFILES table will continue to be accessible during the migration. This type of operation is called online redefinition. CREATE TABLE customer_profiles_interim (id NUMBER, first_name VARCHAR2 (40), last_name VARCHAR2 (80), profile_info BLOB) LOB(profile_info) STORE AS SECUREFILE (TABLESPACE sf_tbs1);

258 Copyright © 2007, Oracle. All rights reserved Migrating from BasicFile to SecureFile Format Call the DBMS_REDEFINITION package to perform the online redefinition operation: connect DECLARE error_count PLS_INTEGER := 0; BEGIN DBMS_REDEFINITION.START_REDEF_TABLE ('OE1', 'customer_profiles', 'customer_profiles_interim', 'id id, first_name first_name, last_name last_name, profile_info profile_info', OPTIONS_FLAG => DBMS_REDEFINITION.CONS_USE_ROWID); DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS ('OE1', 'customer_profiles', 'customer_profiles_interim', 1, true,true,true,false, error_count); DBMS_OUTPUT.PUT_LINE('Errors := ' || TO_CHAR(error_count)); DBMS_REDEFINITION.FINISH_REDEF_TABLE ('OE1', 'customer_profiles', 'customer_profiles_interim'); END;

259 Copyright © 2007, Oracle. All rights reserved Lesson Agenda SecureFile LOB features Deduplication, compression, and encryption Migration of BasicFile LOBs to the SecureFile LOB format Performance of LOBs

260 Copyright © 2007, Oracle. All rights reserved Comparing Performance Compare the performance on loading and reading LOB columns in the SecureFile and BasicFile formats: Performance Comparison Loading DataReading Data SecureFile format00:00: :00:01.09 BasicFile format00:00: :00:01.15

261 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Describe SecureFile LOB features Enable SecureFile LOB deduplication, compression, and encryption Migrate BasicFile LOBs to the SecureFile LOB format Analyze the performance of LOBs

262 Copyright © 2007, Oracle. All rights reserved Practice 8 Overview: Using SecureFile Format LOBs This practice covers the following topics: Setting up the environment for LOBs Migrating BasicFile LOBs to SecureFile LOBs Enabling deduplication and compression

263 Copyright © 2007, Oracle. All rights reserved Notes Page Only

264 Copyright © 2007, Oracle. All rights reserved Notes Page Only

265 Copyright © 2007, Oracle. All rights reserved Notes Page Only

266 Copyright © 2007, Oracle. All rights reserved Notes Page Only

267 9 Copyright © 2007, Oracle. All rights reserved. Using the Data Warehousing Usability Enhancements

268 Copyright © 2007, Oracle. All rights reserved Objectives After completing this lesson, you should be able to: Identify the benefits of pivoting and unpivoting operations Write cross-tab queries to pivot (rotate) column values into new columns and to unpivot (rotate) columns into column values Pivot and unpivot with multiple columns and multiple aggregates Use wildcards and aliases with pivoting operations

269 Copyright © 2007, Oracle. All rights reserved Benefits of Using Pivoting Operations Data returned by business intelligence (BI) queries is more useful if presented in a cross-tabular format. Pivoting enables you to transform multiple rows of input into fewer rows, generally with more columns. When pivoting, an aggregation operator is applied, enabling the query to condense large data sets into smaller, more readable results. Performing pivots on the server side can: –Enhance processing speed –Reduce network load

270 Copyright © 2007, Oracle. All rights reserved PIVOT and UNPIVOT Clauses of the SELECT Statement You can use the PIVOT operator of the SELECT statement to write cross-tabulation queries that rotate the column values into new columns, aggregating data in the process. You can use the UNPIVOT operator of the SELECT statement to rotate columns into values of a column. PIVOT UNPIVOT

271 Copyright © 2007, Oracle. All rights reserved Pivoting on the QUARTER Column: Conceptual Example 30,000 40,000 60,000 30,000 40,000 20,000 AMOUNT_ SOLD 2,500Q1IUSAKids Jeans 2,000Q2CJapanKids Jeans 2,000Q3SUSAShorts I P C CHANNEL Kids Jeans Shorts PRODUCT 1,000Q2Germany 1,500Q4USA Q2 QUARTER 2,500Poland QUANTITY_ SOLD COUNTRY 2,000 Q3 Kids Jeans Shorts PRODUCT 3,500 2,000 Q2 1,500 2,500 Q4Q1

272 Copyright © 2007, Oracle. All rights reserved PIVOT Clause Syntax table_reference PIVOT [ XML ] ( aggregate_function ( expr ) [[AS] alias ] [, aggregate_function ( expr ) [[AS] alias ] ]... pivot_for_clause pivot_in_clause ) -- Specify the column(s) to pivot whose values are to -- be pivoted into columns. pivot_for_clause = FOR { column |( column [, column]... ) } -- Specify the pivot column values from the columns you -- specified in the pivot_for_clause. pivot_in_clause = IN ( { { { expr | ( expr [, expr]... ) } [ [ AS] alias] }... | subquery | { ANY | ANY [, ANY]...} } )

273 Copyright © 2007, Oracle. All rights reserved

274 Copyright © 2007, Oracle. All rights reserved Creating a New View: Example CREATE OR REPLACE VIEW sales_view AS SELECT prod_name AS product, country_name AS country, channel_id AS channel, SUBSTR(calendar_quarter_desc, 6,2) AS quarter, SUM(amount_sold) AS amount_sold, SUM(quantity_sold) AS quantity_sold FROM sh.sales, sh.times, sh.customers, sh.countries, sh.products WHERE sales.time_id = times.time_id AND sales.prod_id = products.prod_id AND sales.cust_id = customers.cust_id AND customers.country_id = countries.country_id GROUP BY prod_name, country_name, channel_id, SUBSTR(calendar_quarter_desc, 6, 2);

275 Copyright © 2007, Oracle. All rights reserved

276 Copyright © 2007, Oracle. All rights reserved Selecting the SALES_VIEW Data SELECT product, country, channel, quarter, quantity_sold FROM sales_view; PRODUCT COUNTRY CHANNEL QUARTER QUANTITY_SOLD Y Box Italy Y Box Italy Y Box Italy Y Box Japan Y Box Japan Y Box Japan Y Box Japan Y Box Japan Bounce Italy Bounce Italy rows selected.

277 Copyright © 2007, Oracle. All rights reserved Pivoting on the QUARTER Column in the SALES_VIEW Data: Example SELECT * FROM (SELECT product, quarter, quantity_sold FROM sales_view) PIVOT (sum(quantity_sold) FOR quarter IN ('01', '02', '03', '04')) ORDER BY product DESC; PRODUCT '01' '02' '03' '04' Y Box Xtend Memory Unix/Windows 1-user Standard Mouse Smash up Boxing rows selected.

278 Copyright © 2007, Oracle. All rights reserved

279 Copyright © 2007, Oracle. All rights reserved Pivoting on the ORDER_MODE Column in the OE Schema: Example CREATE TABLE pivot_table AS SELECT * FROM (SELECT EXTRACT(YEAR FROM order_date) year, order_mode, order_total FROM orders) PIVOT (SUM(order_total) FOR order_mode IN ('direct' AS Store, 'online' AS Internet)) ORDER BY year; SELECT * FROM pivot_table ORDER BY year; YEAR STORE INTERNET rows selected.

280 Copyright © 2007, Oracle. All rights reserved Pivoting on Multiple Columns To pivot on more than one column: –A pivoting column is required to be a column of the table reference on which the pivot is operating –The pivoting column cannot be an arbitrary expression If you need to pivot on an expression, you should alias the expression in a view before the pivot operation.

281 Copyright © 2007, Oracle. All rights reserved Pivoting on Multiple Columns PRODUCT DIRECT_SALES_Q1 INTERNET_SALES_Q Y Box Xtend Memory Unix/Windows 1-user pack Standard Mouse Smash up Boxing rows selected. SELECT * FROM (SELECT product, channel, quarter, quantity_sold FROM sales_view) PIVOT (sum(quantity_sold) FOR (channel, quarter) IN ((3, '01') AS Direct_Sales_Q1, (4, '01') AS Internet_Sales_Q1)) ORDER BY product DESC;

282 Copyright © 2007, Oracle. All rights reserved Pivoting Using Multiple Aggregations SELECT * FROM (SELECT product, channel, amount_sold, quantity_sold FROM sales_view) PIVOT (SUM(amount_sold) AS sums, SUM(quantity_sold) as sumq FOR channel IN (3 AS Dir_Sales, 4 AS Int_Sales)) ORDER BY product DESC; PRODUCT DIR_SALES_SUMS DIR_SALES_SUMQ INT_SALES_SUMS INT_SALES_SUMQ Y Box Xtend Memory Unix/Windows Standard Mouse Smash up Boxing rows selected.

283 Copyright © 2007, Oracle. All rights reserved Distinguishing PIVOT -Generated Nulls from Nulls in the Source Data SELECT * FROM sales2; PROD_ID QTR AMOUNT_SOLD Q Q Q2 200 Q1 50 SELECT * FROM ( SELECT prod_id, qtr, amount_sold FROM sales2) PIVOT (SUM(amount_sold), COUNT(*) AS count_total FOR qtr IN ('Q1', 'Q2') ) ORDER BY prod_id DESC; PROD_ID Q1 Q1_COUNT_TOTAL Q2 Q2_COUNT_TOTAL

284 Copyright © 2007, Oracle. All rights reserved Using the XML Keyword to Specify Pivot Values: Two Methods ANY If you use the XML keyword with the PIVOT syntax Use the ANY keyword, or Use a subquery XML The XML string for each row includes only the pivot values found in the input data for that row. The XML string includes all pivot values found by the subquery even if there are no aggregate values.

285 Copyright © 2007, Oracle. All rights reserved Specifying PIVOT Values: Using the ANY Keyword PRODUCT CHANNEL_XML MB External 3.5" Diskette 3 rows selected. SET LONG 1024; SELECT * FROM (SELECT product, channel, quantity_sold FROM sales_view ) PIVOT XML (SUM(quantity_sold) FOR channel IN (ANY) ) ORDER BY product DESC;

286 Copyright © 2007, Oracle. All rights reserved Specifying PIVOT Values: Using Subqueries PRODUCT CHANNEL_XML Y Box 9 1 2 3 SELECT * FROM (SELECT product, channel, quantity_sold FROM sales_view ) PIVOT XML(SUM(quantity_sold) FOR channel IN (SELECT distinct channel_id FROM sh.channels));

287 Copyright © 2007, Oracle. All rights reserved Unpivoting on the QUARTER Column: Conceptual Example 2,000 Q3 Kids Jeans Shorts PRODUCT 3,500 2,000 Q2 1,500 2,500 Q4Q1 2,500Q1Kids Jeans 2,000Q2Kids Jeans 3,500Q2Shorts 1,500Q4Kids Jeans Q3 QUARTER 2,000Shorts SUM_OF_QUANTITYPRODUCT

288 Copyright © 2007, Oracle. All rights reserved Using the UNPIVOT Operator An UNPIVOT does not reverse a PIVOT operation; instead, it rotates data from columns into rows. If you are working with pivoted data, an UNPIVOT operation cannot reverse any aggregations that have been made by PIVOT or any other means. UNPIVOT

289 Copyright © 2007, Oracle. All rights reserved Using the UNPIVOT Clause The UNPIVOT clause rotates columns from a previously pivoted table or a regular table into rows. You specify: –The measure columns to be unpivoted –The names for the columns that will result from the unpivot operation –The columns that will be unpivoted back into values of the column specified in the unpivot_for_clause You can use an alias to map the column name to another value.

290 Copyright © 2007, Oracle. All rights reserved Data Types of the Value Columns in an UNPIVOT Operation Data Type for the Value Columns Resulting Unpivoted Column Data Type If ALL the value columns are CHARCHAR If ANY value column is VARCHAR2VARCHAR2 If ALL the value columns are NUMBERNUMBER If ANY value column is BINARY_DOUBLEBINARY_DOUBLE If NO value column is BINARY_DOUBLE but ANY value column is BINARY_FLOAT BINARY_FLOAT

291 Copyright © 2007, Oracle. All rights reserved Unpivot Clause Syntax table_reference UNPIVOT [{INCLUDE|EXCLUDE} NULLS] -- specify the measure column(s) to be unpivoted. ( { column | ( column [, column]... ) } unpivot_for_clause unpivot_in_clause ) -- Specify one or more names for the columns that will -- result from the unpivot operation. unpivot_for_clause = FOR { column | ( column [, column]... ) } -- Specify the columns that will be unpivoted into values of -- the column specified in the pivot_for_clause. unpivot_in_clause = ( { column | ( column [, column]... ) } [ AS { constant | ( constant [, constant]... ) } ] [, { column | ( column [, column]... ) } [ AS { constant | ( constant [, constant]...) } ] ]...)

292 Copyright © 2007, Oracle. All rights reserved Creating a New Pivot Table: Example CREATE TABLE pivotedtable AS SELECT * FROM (SELECT product, quarter, quantity_sold FROM sales_view) PIVOT (sum(quantity_sold) FOR quarter IN ('01' AS Q1, '02' AS Q2, '03' AS Q3, '04' AS Q4)); Table created. SELECT * FROM pivotedtable ORDER BY product DESC; PRODUCT Q1 Q2 Q3 Q Y Box Xtend Memory rows selected.

293 Copyright © 2007, Oracle. All rights reserved Unpivoting on the QUARTER Column in the SH Schema: Example SELECT * FROM pivotedtable UNPIVOT (quantity_sold For Quarter IN (Q1, Q2, Q3, Q4)) ORDER BY product DESC, quarter; PRODUCT QUARTER QUANTITY_SOLD Y Box Q Y Box Q Y Box Q Y Box Q Xtend Memory Q Xtend Memory Q Xtend Memory Q Xtend Memory Q Unix/Windows 1-user pack Q rows selected.

294 Copyright © 2007, Oracle. All rights reserved Unpivoting the ORDER_MODE Column in the OE Schema: Example SELECT * FROM pivot_table UNPIVOT (yearly_total FOR order_mode IN (store AS 'direct', internet AS 'online')) ORDER BY year, order_mode; YEAR ORDER_MODE YEARLY_TOTAL direct direct direct direct online direct online direct online rows selected.

295 Copyright © 2007, Oracle. All rights reserved Unpivoting on Multiple Columns in the SH Schema: Example CREATE TABLE multi_col_pivot AS SELECT * FROM (SELECT product, channel, quarter, quantity_sold FROM sales_view) PIVOT (sum(quantity_sold) FOR (channel, quarter) IN ((3, '01') AS Direct_Sales_Q1, (4, '01') AS Internet_Sales_Q1)) ORDER BY product DESC; Table created. SELECT * FROM multi_col_pivot; PRODUCT DIRECT_SALES_Q1 INTERNET_SALES_Q Y Box Xtend Memory rows selected.

296 Copyright © 2007, Oracle. All rights reserved Unpivoting on Multiple Columns in the SH Schema: Example -- Provide explicit values for the unpivot columns SELECT * FROM multi_col_pivot UNPIVOT (quantity_sold FOR (channel, quarter) IN ( Direct_Sales_Q1 AS ('Direct', 'Q1'), Internet_Sales_Q1 AS ('Internet', 'Q1') ) ) ORDER BY product DESC, quarter; PRODUCT CHANNEL QUARTER QUANTITY_SOLD Y Box Internet Q1 253 Y Box Direct Q1 771 Xtend Memory Internet Q1 350 Xtend Memory Direct Q rows selected.

297 Copyright © 2007, Oracle. All rights reserved Unpivoting on Multiple Aggregations in the SH Schema: Example CREATE TABLE multi_agg_pivot AS SELECT * FROM (SELECT product, channel, quarter, quantity_sold, amount_sold FROM sales_view) PIVOT (sum(quantity_sold) sumq, sum(amount_sold) suma FOR channel IN (3 AS Direct, 4 AS Internet) ) ORDER BY product DESC; Table created. SELECT * FROM multi_agg_pivot; PRODUCT QUARTER DIRECT_SUMQ DIRECT_SUMA INTERNET_SUMQ INTERNET_SUMA Bounce Bounce Bounce Bounce row selected.

298 Copyright © 2007, Oracle. All rights reserved Unpivoting on Multiple Aggregations in the SH Schema: Example SELECT * FROM multi_agg_pivot UNPIVOT ((total_amount_sold, total_quantity_sold) FOR channel IN ((Direct_sumq, Direct_suma)AS 3, (Internet_sumq, Internet_suma)AS 4 )) ORDER BY product DESC, quarter, channel; PRODUCT QUARTER CHANNEL TOTAL_AMOUNT_SOLD TOTAL_QUANTITY_SOLD Bounce Bounce Bounce Bounce Bounce Bounce Bounce Bounce rows selected.

299 Copyright © 2007, Oracle. All rights reserved Summary In this lesson, you should have learned how to: Identify the benefits of pivoting and unpivoting operations Write cross-tab queries to pivot (rotate) column values into new columns and to unpivot (rotate) columns into column values Pivot and unpivot with multiple columns and multiple aggregates Use wildcards and aliases with pivoting operations

300 Copyright © 2007, Oracle. All rights reserved Practice 9 Overview: Pivoting This practice covers the following topics: Using the PIVOT clause with the SELECT statement. Examining special pivoting cases

301 Copyright © 2007, Oracle. All rights reserved Notes Page Only

302 Copyright © 2007, Oracle. All rights reserved Notes Page Only

303 Copyright © 2007, Oracle. All rights reserved Notes Page Only

304 B Copyright © 2007, Oracle. All rights reserved. Table Descriptions and Data

305 Copyright © 2007, Oracle. All rights reserved. B - 305

306 Copyright © 2007, Oracle. All rights reserved. B - 306

307 Copyright © 2007, Oracle. All rights reserved. B - 307

308 Copyright © 2007, Oracle. All rights reserved. B - 308

309 Copyright © 2007, Oracle. All rights reserved. B - 309

310 Copyright © 2007, Oracle. All rights reserved. B - 310

311 Copyright © 2007, Oracle. All rights reserved. B - 311

312 Copyright © 2007, Oracle. All rights reserved. B - 312

313 Copyright © 2007, Oracle. All rights reserved. B - 313

314 Copyright © 2007, Oracle. All rights reserved. B - 314

315 Copyright © 2007, Oracle. All rights reserved. B - 315

316 Copyright © 2007, Oracle. All rights reserved. B - 316

317 C Copyright © 2007, Oracle. All rights reserved. Using the PL/SQL Debugger in SQL Developer

318 Copyright © 2007, Oracle. All rights reserved. C Objectives After completing this lesson, you should be able to do the following: Use the PL/SQL Debugger tool in SQL Developer Step through PL/SQL code line by line Step through called PL/SQL subroutines Analyze data as the routine is running Change variable values at run time Control the execution of a PL/SQL block

319 Copyright © 2007, Oracle. All rights reserved. C Debugging PL/SQL Subprograms Using the SQL Developer Debugger You can use the debugger to control the execution of your PL/SQL program. To debug a PL/SQL subprogram, a security administrator needs to grant the following privileges to the application developer: –DEBUG ANY PROCEDURE –DEBUG CONNECT SESSION

320 Copyright © 2007, Oracle. All rights reserved. C Debugging a Subprogram: Overview 1. Edit procedure2. Add breakpoints3. Compile for Debug 4. Debug 5. Enter parameter value(s) 6. Choose debugging tool, and monitor data

321 Copyright © 2007, Oracle. All rights reserved. C The Procedure or Function Code Editing Tab

322 Copyright © 2007, Oracle. All rights reserved. C The Procedure or Function Tab Toolbar IconDescription 1. Run Starts normal execution of the function or procedure, and displays the results on the Running - Log tabbed page 2. Debug Starts execution of the subprogram in debug mode, and displays the Debugging - Log tabbed page, which includes the debugging toolbar for controlling the execution 3. Compile Performs a PL/SQL compilation of the subprogram 4. Compile for Debug Performs a PL/SQL compilation so that it can be debugged

323 Copyright © 2007, Oracle. All rights reserved. C The Debugging – Log Tab Toolbar IconDescription 1. Find Execution Point Goes to the next execution point 2. Resume Continues execution 3. Step Over Bypasses the next subprogram and goes to the next statement after the subprogram 4. Step Into Executes a single program statement at a time. If the execution point is located on a call to a subprogram, it steps into the first statement in that subprogram. 5. Step Out Leaves the current subprogram and goes to the next statement with a breakpoint

324 Copyright © 2007, Oracle. All rights reserved. C The Debugging – Log Tab Toolbar IconDescription 6. Step to End of Method Goes to last statement in the current subprogram (or to the next breakpoint if there are any in the current procedure) 7. Pause Halts execution but does not exit 8. Terminate Halts and exits the execution Displays breakpoints

325 Copyright © 2007, Oracle. All rights reserved. C Additional Tabs TabDescription Data Located under the code text area, displays information about all variables Watches Located under the code text area, displays information about watchpoints

326 Copyright © 2007, Oracle. All rights reserved. C Debugging a Procedure Example: Creating a New emp_list Procedure

327 Copyright © 2007, Oracle. All rights reserved. C Debugging a Procedure Example: Creating a New get_location Function

328 Copyright © 2007, Oracle. All rights reserved. C Setting Breakpoints and Compiling emp_list in Debug Mode

329 Copyright © 2007, Oracle. All rights reserved. C Compiling the get_location Function for Debug Mode

330 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list and Enter Value for PMAXROWS Parameter Enter the procedures Parameter value using the Anonymous block.

331 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list : Step Into the Code Program control stops at first breakpoint. 1 2

332 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list: Step Into the Code Step Into [F7]: Steps into and executes the cursor code. Control is transferred to Cursor definition 1 2

333 Copyright © 2007, Oracle. All rights reserved. C Viewing the Data

334 Copyright © 2007, Oracle. All rights reserved. C Modifying the Variables While Debugging the Code

335 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list : Step Over the Code 1 2 Step Over [F8]: Executes the Cursor (same as [F7]) But control is not transferred to Open Cursor code

336 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list : Step Out of the Code ( [SHIFT]+[F7] )

337 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list : Run to Cursor [ F4 ] Run to Cursor (F4): Run to your cursor location without having to single step or set a breakpoint.

338 Copyright © 2007, Oracle. All rights reserved. C Debugging emp_list : Step to End of Method Loops until i <> PMAXROWS

339 Copyright © 2007, Oracle. All rights reserved. C Summary In this lesson, you should have learned how to debug procedures and functions.

340 Copyright © 2007, Oracle. All rights reserved. C - 340

341 D Copyright © 2007, Oracle. All rights reserved. Using SQL*Plus

342 Copyright © 2007, Oracle. All rights reserved. D Objectives After completing this appendix, you should be able to do the following: Log in to SQL*Plus Edit SQL commands Format output using SQL*Plus commands Interact with script files

343 Copyright © 2007, Oracle. All rights reserved. D SQL and SQL*Plus Interaction Buffer Server SQL statements Query results SQL scripts SQL*Plus

344 Copyright © 2007, Oracle. All rights reserved. D SQL Statements Versus SQL*Plus Commands A language ANSI-standard Keywords cannot be abbreviated Statements manipulate data and table definitions in the database SQL statements SQLSQL*Plus SQL buffer SQL*Plus commands SQL*Plus buffer An environment Oracle-proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database

345 Copyright © 2007, Oracle. All rights reserved. D Overview of SQL*Plus Log in to SQL*Plus Describe the table structure Edit your SQL statement Execute SQL from SQL*Plus Save SQL statements to files and append SQL statements to files Execute saved files Load commands from file to buffer to edit

346 Copyright © 2007, Oracle. All rights reserved. D sqlplus Logging In to SQL*Plus 1 2

347 Copyright © 2007, Oracle. All rights reserved. D Changing the Settings of SQL*Plus Environment

348 Copyright © 2007, Oracle. All rights reserved. D Displaying Table Structure Use the SQL*Plus DESCRIBE command to display the structure of a table: DESC[RIBE] tablename

349 Copyright © 2007, Oracle. All rights reserved. D Displaying Table Structure Name Null? Type DEPARTMENT_ID NOT NULL NUMBER(4) DEPARTMENT_NAME NOT NULL VARCHAR2(30) MANAGER_ID NUMBER(6) LOCATION_ID NUMBER(4) DESCRIBE departments

350 Copyright © 2007, Oracle. All rights reserved. D SQL*Plus Editing Commands A[PPEND] text C[HANGE] / old / new C[HANGE] / text / CL[EAR] BUFF[ER] DEL DEL n DEL m n

351 Copyright © 2007, Oracle. All rights reserved. D SQL*Plus Editing Commands I[NPUT] I[NPUT] text L[IST] L[IST] n L[IST] m n R[UN] n n text 0 text

352 Copyright © 2007, Oracle. All rights reserved. D Using LIST, n, and APPEND LIST 1 SELECT last_name 2* FROM employees 1 1* SELECT last_name A, job_id 1* SELECT last_name, job_id LIST 1 SELECT last_name, job_id 2* FROM employees

353 Copyright © 2007, Oracle. All rights reserved. D Using the CHANGE Command LIST 1* SELECT * from employees c/employees/departments 1* SELECT * from departments LIST 1* SELECT * from departments

354 Copyright © 2007, Oracle. All rights reserved. D SQL*Plus File Commands SAVE filename GET filename START filename EDIT filename SPOOL filename EXIT

355 Copyright © 2007, Oracle. All rights reserved. D Using the SAVE, START, and EDIT Commands LIST 1 SELECT last_name, manager_id, department_id 2* FROM employees SAVE my_query Created file my_query START my_query LAST_NAME MANAGER_ID DEPARTMENT_ID King 90 Kochhar rows selected.

356 Copyright © 2007, Oracle. All rights reserved. D Using the SAVE, START, and EDIT Commands EDIT my_query

357 Copyright © 2007, Oracle. All rights reserved. D SERVEROUTPUT Command Use the SET SERVEROUT[PUT] command to control whether to display the output of stored procedures or PL/SQL blocks in SQL*Plus. The DBMS_OUTPUT line length limit is increased from 255 bytes to 32,767 bytes. The default size is now unlimited. Resources are not preallocated when SERVEROUTPUT is set. Because there is no performance penalty, use UNLIMITED unless you want to conserve physical memory. SET SERVEROUT[PUT] {ON | OFF} [SIZE {n | UNL[IMITED]}] [FOR[MAT] {WRA[PPED] | WOR[D_WRAPPED] | TRU[NCATED]}]

358 Copyright © 2007, Oracle. All rights reserved. D Using the SQL*Plus SPOOL Command SPO[OL] [file_name[.ext] [CRE[ATE] | REP[LACE] | APP[END]] | OFF | OUT] OptionDescription file_name[.ext] Spools output to the specified file name CRE[ATE] Creates a new file with the name specified REP[LACE] Replaces the contents of an existing file. If the file does not exist, REPLACE creates the file. APP[END] Adds the contents of the buffer to the end of the file that you specify OFF Stops spooling OUT Stops spooling and sends the file to your computers standard (default) printer

359 Copyright © 2007, Oracle. All rights reserved. D Using the AUTOTRACE Command It displays a report after the successful execution of SQL DML statements, such as SELECT, INSERT, UPDATE, or DELETE. The report can now include execution statistics and the query execution path. SET AUTOT[RACE] {ON | OFF | TRACE[ONLY]} [EXP[LAIN]] [STAT[ISTICS]] SET AUTOTRACE ON -- The AUTOTRACE report includes both the optimizer -- execution path and the SQL statement execution -- statistics.

360 Copyright © 2007, Oracle. All rights reserved. D Summary In this appendix, you should have learned how to use SQL*Plus as an environment to do the following: Execute SQL statements Edit SQL statements Format output Interact with script files

361 E Copyright © 2007, Oracle. All rights reserved. Working with Collections

362 Copyright © 2007, Oracle. All rights reserved. E Objectives After completing this lesson, you should be able to do the following: Describe an object type Create an object type specification Implement the constructor method on objects Create collections –Nested table collections –Varray collections Use collections methods Manipulate collections

363 Copyright © 2007, Oracle. All rights reserved. E Understanding Collections A collection is a group of elements, all of the same type. Collections work like arrays. Collections can store instances of an object type and, conversely, can be attributes of an object type. Types of collections in PL/SQL: –Nested tables –Varrays –Associative arrays –String-indexed collections – INDEX BY pls_integer

364 Copyright © 2007, Oracle. All rights reserved. E Nested table: Varray: Describing the Collection Types

365 Copyright © 2007, Oracle. All rights reserved. E - 365

366 Copyright © 2007, Oracle. All rights reserved. E Listing Characteristics for Collections PL/SQL Nested Tables DB Nested Tables PL/SQL Varrays DB Varrays Maximum size No Yes SparsityCan beNoDense StorageN/A Stored out of line N/A Stored inline (if < 4,000 bytes) Ordering Does not retain ordering and subscripts Retains ordering and subscripts

367 Copyright © 2007, Oracle. All rights reserved. E Using Collections Effectively Varrays involve fewer disk accesses and are more efficient. Use nested tables for storing large amounts of data. Use varrays to preserve the order of elements in the collection column. If you do not have a requirement to delete elements in the middle of a collection, favor varrays. Varrays do not allow piecewise updates.

368 Copyright © 2007, Oracle. All rights reserved. E Creating Collection Types Nested table in the database: Nested table in PL/SQL: Varray in the database: Varray in PL/SQL: CREATE [OR REPLACE] TYPE type_name AS TABLE OF Element_datatype [NOT NULL]; CREATE [OR REPLACE] TYPE type_name AS VARRAY (max_elements) OF element_datatype [NOT NULL]; TYPE type_name IS TABLE OF element_datatype [NOT NULL]; TYPE type_name IS VARRAY (max_elements) OF element_datatype [NOT NULL];

369 Copyright © 2007, Oracle. All rights reserved. E Declaring Collections: Nested Table First, define an object type: Second, declare a column of that collection type: CREATE TYPE typ_item AS OBJECT --create object (prodid NUMBER(5), price NUMBER(7,2) ) / CREATE TYPE typ_item_nst -- define nested table type AS TABLE OF typ_item / CREATE TABLE pOrder ( -- create database table ordidNUMBER(5), supplierNUMBER(5), requesterNUMBER(4), orderedDATE, itemstyp_item_nst) NESTED TABLE items STORE AS item_stor_tab / 1 2 3

370 Copyright © 2007, Oracle. All rights reserved. E Supplier Requester Ordered Items pOrder nested table MAR FEB-97 Understanding Nested Table Storage Nested tables are stored out-of-line in storage tables. Storage table $ $ $ 0.22 $ NESTED_TABLE_ID ProdIDPrice

371 Copyright © 2007, Oracle. All rights reserved. E CREATE TABLE department ( -- create database table dept_id NUMBER(2), name VARCHAR2(15), budget NUMBER(11,2), projects typ_ProjectList) -- declare varray as column / Declaring Collections: Varray First, define a collection type: Then, declare a collection of that type: CREATE TYPE typ_Project AS OBJECT( --create object project_no NUMBER(2), title VARCHAR2(35), cost NUMBER(7,2)) / CREATE TYPE typ_ProjectList AS VARRAY (50) OF typ_Project -- define VARRAY type / 1 2 3

372 Copyright © 2007, Oracle. All rights reserved. E CREATE OR REPLACE PACKAGE manage_dept_proj AS TYPE typ_proj_details IS TABLE OF typ_Project;... PROCEDURE allocate_proj (propose_proj IN typ_proj_details); FUNCTION top_project (n NUMBER) RETURN typ_proj_details;... Working with Collections in PL/SQL You can declare collections as formal parameters of procedures and functions. You can specify a collection type in the RETURN clause of a function specification. Collections follow the usual scoping and instantiation rules.

373 Copyright © 2007, Oracle. All rights reserved. E Initializing Collections Three ways to initialize: Use a constructor. Fetch from the database. Assign another collection variable directly. DECLARE --this example uses a constructor v_accounting_project typ_ProjectList; BEGIN v_accounting_project := typ_ProjectList (typ_Project (1, 'Dsgn New Expense Rpt', 3250), typ_Project (2, 'Outsource Payroll', 12350), typ_Project (3, 'Audit Accounts Payable',1425)); INSERT INTO department VALUES(10, 'Accounting', 123, v_accounting_project);... END; /

374 Copyright © 2007, Oracle. All rights reserved. E DECLARE -- this example uses a fetch from the database v_accounting_project typ_ProjectList; BEGIN SELECT projects INTO v_accounting_project FROM department WHERE dept_id = 10;... END; / Initializing Collections DECLARE -- this example assigns another collection -- variable directly v_accounting_project typ_ProjectList; v_backup_project typ_ProjectList; BEGIN SELECT projects INTO v_accounting_project FROM department WHERE dept_id = 10; v_backup_project := v_accounting_project; END; / 1 2

375 Copyright © 2007, Oracle. All rights reserved. E Referencing Collection Elements Use the collection name and a subscript to reference a collection element: Syntax: Example: To reference a field in a collection: collection_name(subscript) v_accounting_project(1) v_accounting_project(1).cost

376 Copyright © 2007, Oracle. All rights reserved. E Using Collection Methods EXISTS COUNT LIMIT FIRST and LAST PRIOR and NEXT EXTEND TRIM DELETE collection_name.method_name [(parameters)]

377 Copyright © 2007, Oracle. All rights reserved. E DECLARE i INTEGER; v_accounting_project typ_ProjectList; BEGIN v_accounting_project := typ_ProjectList( typ_Project (1,'Dsgn New Expense Rpt', 3250), typ_Project (2, 'Outsource Payroll', 12350), typ_Project (3, 'Audit Accounts Payable',1425)); i := v_accounting_project.FIRST ; WHILE i IS NOT NULL LOOP IF v_accounting_project(i).cost > then DBMS_OUTPUT.PUT_LINE('Project too expensive: ' || v_accounting_project(i).title); END IF; i := v_accounting_project.NEXT (i); END LOOP; END; / Using Collection Methods Traverse collections with methods:

378 Copyright © 2007, Oracle. All rights reserved. E DECLARE v_my_projects typ_ProjectList; v_array_count INTEGER; v_last_element INTEGER; BEGIN SELECT projects INTO v_my_projects FROM department WHERE dept_id = 10; v_array_count := v_my_projects.COUNT ; dbms_output.put_line('The # of elements is: ' || v_array_count); v_my_projects.EXTEND ; --make room for new project v_last_element := v_my_projects.LAST ; dbms_output.put_line('The last element is: ' || v_last_element); IF v_my_projects.EXISTS(5) THEN dbms_output.put_line('Element 5 exists!'); ELSE dbms_output.put_line('Element 5 does not exist.'); END IF; END; / Using Collection Methods

379 Copyright © 2007, Oracle. All rights reserved. E CREATE OR REPLACE PROCEDURE add_project ( p_deptno IN NUMBER, p_new_project IN typ_Project, p_position IN NUMBER ) IS v_my_projects typ_ProjectList; BEGIN SELECT projects INTO v_my_projects FROM department WHERE dept_id = p_deptno FOR UPDATE OF projects; v_my_projects.EXTEND; --make room for new project /* Move varray elements forward */ FOR i IN REVERSE p_position..v_my_projects.LAST - 1 LOOP v_my_projects(i + 1) := v_my_projects(i); END LOOP; v_my_projects(p_position) := p_new_project; -- add new -- project UPDATE department SET projects = v_my_projects WHERE dept_id = p_deptno; END add_project; / Manipulating Individual Elements

380 Copyright © 2007, Oracle. All rights reserved. E Avoiding Collection Exceptions Common exceptions with collections: COLLECTION_IS_NULL NO_DATA_FOUND SUBSCRIPT_BEYOND_COUNT SUBSCRIPT_OUTSIDE_LIMIT VALUE_ERROR

381 Copyright © 2007, Oracle. All rights reserved. E Common exceptions with collections: DECLARE TYPE NumList IS TABLE OF NUMBER; nums NumList; -- atomically null BEGIN /* Assume execution continues despite the raised exceptions. */ nums(1) := 1; -- raises COLLECTION_IS_NULL nums := NumList(1,2); -- initialize table nums(NULL) := 3 -- raises VALUE_ERROR nums(0) := 3; -- raises SUBSCRIPT_OUTSIDE_LIMIT nums(3) := 3; -- raises SUBSCRIPT_BEYOND_COUNT nums.DELETE(1); -- delete element 1 IF nums(1) = 1 THEN -- raises NO_DATA_FOUND... Avoiding Collection Exceptions

382 Copyright © 2007, Oracle. All rights reserved. E Summary In this lesson, you should have learned how to: Identify types of collections –Nested tables –Varrays Define nested tables and varrays in the database Define nested tables and varrays in PL/SQL –Access collection elements –Use collection methods in PL/SQL –Identify raised exceptions with collections –Decide which collection type is appropriate for each scenario

383 F Copyright © 2007, Oracle. All rights reserved. Exploring the Data Warehousing Performance Enhancements

384 Copyright © 2007, Oracle. All rights reserved. F Objectives After completing this lesson, you should be able to: List the materialized view enhancements: –Review the materialized view concepts –List the new and updated MV catalog views –Describe the updated columns in the MV catalog views –Identify the refresh performance enhancements –Review the benefits of using materialized views

385 Copyright © 2007, Oracle. All rights reserved. F Objectives List the query rewrite enhancements: –Review the benefits of query rewrite –Use the query rewrite enhancement to support queries with inline views –Identify the query rewrite enhancement that supports queries with remote tables

386 Copyright © 2007, Oracle. All rights reserved. F Lesson Agenda Materialized view enhancements: –Concepts –New and updated MV catalog views –Refresh performance enhancements –Benefits of using materialized views Query rewrite enhancements: –Query rewrite benefits –Query rewrite enhancements with inline views –Query rewrite enhancements with remote tables

387 Copyright © 2007, Oracle. All rights reserved. F Materialized View: Overview Materialized views are: Schema objects Used to summarize, compute, replicate, and distribute data Used in data warehouse, decision support, distributed or mobile computing environments

388 Copyright © 2007, Oracle. All rights reserved. F Materialized View: Overview Sample materialized view (in the SH sample schema): DESCRIBE sh.FWEEK_PSCAT_SALES_MV Name Null Type WEEK_ENDING_DAY NOT NULL DATE PROD_SUBCATEGORY NOT NULL VARCHAR2(50) DOLLARS NUMBER CHANNEL_ID NOT NULL NUMBER PROMO_ID NOT NULL NUMBER

389 Copyright © 2007, Oracle. All rights reserved. F New and Updated MV Catalog Views New catalog views display the partition change tracking (PCT) information for a given materialized view. New catalog views display which sections of the materialized views data are fresh or stale. You can view the partition staleness information of the materialized view. It affects the usability and maintainability of the materialized view.

390 Copyright © 2007, Oracle. All rights reserved. F PCT Catalog Views Showing Stalessness Corresponding to Base Partitions USER/ALL/DBA_MVIEW_DETAIL _RELATIONS views (UPDATED) USER/ALL/DBA_MVIEW_DETAIL_ SUBPARTITION views (NEW) USER/ALL/DBA_MVIEW_DETAIL_ PARTITION views (NEW) USER/ALL/DBA_MVIEWS views (UPDATED)

391 Copyright © 2007, Oracle. All rights reserved. F Important Instructions

392 Copyright © 2007, Oracle. All rights reserved. F New Columns in the USER/ALL/DBA_MVIEWS Catalog View NUM_PCT_TABLES : Specifies the number of PCT detail tables NUM_FRESH_PCT_REGIONS : Specifies the number of fresh PCT partition regions NUM_STALE_PCT_REGIONS : Specifies the number of stale PCT partition regions SELECT mview_name, num_pct_tables, num_fresh_pct_regions, num_stale_pct_regions FROM all_mviews WHERE owner = 'SH'; MVIEW_NAME NUM_PCT_TABLES NUM_FRESH_PCT_REGIONS NUM_STALE_PCT_REGIONS FWEEK_PSCAT_ SALES_MV

393 Copyright © 2007, Oracle. All rights reserved. F DETAILOBJ_PCT : Is the detail object PCT supported NUM_FRESH_PCT_PARTITIONS : Specifies the number of fresh PCT partitions NUM_STALE_PCT_PARTITIONS : Specifies the number of stale PCT partitions DESCRIBE all_mview_detail_relations Name Null Type OWNER NOT NULL VARCHAR2(30) MVIEW_NAME NOT NULL VARCHAR2(30) DETAILOBJ_OWNER NOT NULL VARCHAR2(30) DETAILOBJ_NAME NOT NULL VARCHAR2(30) DETAILOBJ_TYPE VARCHAR2(9) DETAILOBJ_ALIAS VARCHAR2(30) DETAILOBJ_PCT VARCHAR2(1) NUM_FRESH_PCT_PARTITIONS NUMBER NUM_STALE_PCT_PARTITIONS NUMBER New Columns in USER/ALL/DBA_MVIEW_DETAIL_RELATIONS

394 Copyright © 2007, Oracle. All rights reserved. F New USER/ALL/DBA_MVIEW_DETAIL_PARTITION Catalog View SELECT detailobj_owner, detailobj_name, detail_partition_name, detail_partition_position POSITION, freshness FRESH FROM all_mview_detail_partition WHERE mview_name = 'FWEEK_PSCAT_SALES_MV'; DETAIL_OBJ_OWNER DETAIL_OBJ_NAME DETAIL_PARTITION_NAME POSITION FRESH SH SALES SALES_ FRESH SH SALES SALES_ FRESH SH SALES SALES_H1_ FRESH SH SALES SALES_H2_ FRESH SH SALES SALES_Q1_ FRESH... SH SALES SALES_Q1_ FRESH SH SALES SALES_Q2_ FRESH SH SALES SALES_Q3_ FRESH SH SALES SALES_Q4_ FRESH 28 rows selected

395 Copyright © 2007, Oracle. All rights reserved. F New Catalog View: USER/ALL/DBA_MVIEW_DETAIL_SUBPARTITION DESCRIBE all_mview_detail_subpartition Name Null Type OWNER NOT NULL VARCHAR2(30) MVIEW_NAME NOT NULL VARCHAR2(30) DETAILOBJ_OWNER NOT NULL VARCHAR2(30) DETAILOBJ_NAME NOT NULL VARCHAR2(30) DETAIL_PARTITION_NAME VARCHAR2(30) DETAIL_SUBPARTITION_NAME VARCHAR2(30) DETAIL_SUBPARTITION_POSITION NUMBER FRESHNESS CHAR(5)

396 Copyright © 2007, Oracle. All rights reserved. F Refresh Performance Improvements in Oracle Database 11g Refresh operations on materialized views are now faster with the following improvements: Refresh statement combinations (merge and delete) Removal of unnecessary refresh hint Index creation for UNION ALL MV PCT refresh possible for UNION ALL MV

397 Copyright © 2007, Oracle. All rights reserved. F Using Summaries to Improve Performance Special types of aggregate views Improve query execution time by precalculating expensive joins and aggregation operations prior to execution and storing results in a database table Created with a materialized view

398 Copyright © 2007, Oracle. All rights reserved. F Summary Management DBA creates materialized view (summary table) End user queries tables and views Oracle server rewrites SQL query to use summary tables

399 Copyright © 2007, Oracle. All rights reserved. F Summary Management Components Mechanisms to define materialized views and dimensions Refresh mechanism to ensure materialized views contain the latest data Query rewrite capability to transparently rewrite a query to use a materialized view SQL Access Advisor: Recommends materialized views and indexes to be created DBMS_ADVISOR.TUNE_MVIEW procedure: Shows you how to make your materialized view fast refreshable and use general query rewrite

400 Copyright © 2007, Oracle. All rights reserved. F Using Summary Management 1.Use the SQL Access Advisor to determine how you will use materialized views. 2.Create materialized views and design how queries will be rewritten. 3.Use DBMS_ADVISOR.TUNE_MVIEW to obtain an optimized materialized view as necessary. 4.View the CREATE output results by querying USER_TUNE_MVIEW or DBA_TUNE_MVIEW. DBMS_ADVISOR.TUNE_MVIEW ( name, 'CREATE MATERIALIZED VIEW my_mv_name REFRESH FAST AS SELECT_statement_goes_here);

401 Copyright © 2007, Oracle. All rights reserved. F Lesson Agenda Materialized view enhancements: –Concepts –New and updated MV catalog views –Refresh performance enhancements –Benefits of using materialized views Query rewrite enhancements: –Query rewrite benefits –Query rewrite enhancements with inline views –Query rewrite enhancements with remote tables

402 Copyright © 2007, Oracle. All rights reserved. F Query Rewrite: Overview Tries to use materialized views instead of base tables to return query results Can save orders of magnitude of CPU and elapsed time to return results as queries are precomputed Query does not necessarily have to be in the exact form of the materialized view query to rewrite Various requirements for query rewrite to occur Query rewrite

403 Copyright © 2007, Oracle. All rights reserved. F Important Instructions

404 Copyright © 2007, Oracle. All rights reserved. F Cost-Based Query Rewrite Process Query rewriteGenerate plan Compare plan costs Generate planPick best plan End user queries tables and views

405 Copyright © 2007, Oracle. All rights reserved. F What Can Be Rewritten? Queries and subqueries in the following types of SQL statements: – SELECT – CREATE TABLE … AS SELECT – INSERT INTO … SELECT Subqueries in DML statements: – INSERT – UPDATE – DELETE Subqueries in the set operators: – UNION – UNION ALL – INTERSECT – MINUS

406 Copyright © 2007, Oracle. All rights reserved. F Query Rewrite Enhancement to Support Queries Containing Inline Views Query with inline view Query inline view s (IV) text matches the MV s IV text? Rewrite query Yes Query inline view s (IV) text equivalent to the MV s IV text? No query rewrite Yes No

407 Copyright © 2007, Oracle. All rights reserved. F When Are Two Inline Views Equivalent? Two inline views are considered equivalent when: The SELECT lists and GROUP BY lists are equivalent The FROM clauses contain the same or equivalent objects The join graphs, including all the selections in the WHERE clauses are equivalent The HAVING clauses are equivalent

408 Copyright © 2007, Oracle. All rights reserved. F An MV Inline View Text Matches a Querys Inline View Text: Example CREATE MATERIALIZED VIEW SUM_SALES_MV ENABLE QUERY REWRITE AS SELECT mv_iv.prod_id, mv_iv.cust_id, sum(mv_iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM sales, products WHERE sales.prod_id = products.prod_id) MV_IV GROUP BY mv_iv.prod_id, mv_iv.cust_id; -- The text of the IV matches exactly the text of the -- MV; therefore, the query is rewritten with the MV SELECT iv.prod_id, iv.cust_id, SUM(iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM sales, products WHERE sales.prod_id = products.prod.id) IV GROUP BY iv.prod_id, iv.cust_id; 1 2

409 Copyright © 2007, Oracle. All rights reserved. F An MV Inline View Text is Equivalent to a Querys Inline View Text: Example CREATE MATERIALIZED VIEW SUM_SALES_MV ENABLE QUERY REWRITE AS SELECT mv_iv.prod_id, mv_iv.cust_id, sum(mv_iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM sales, products WHERE sales.prod_id = products.prod_id) MV_IV GROUP BY mv_iv.prod_id, mv_iv.cust_id; -- The text of the IV doesnt match the text of the MV; -- however, they are equivalent SELECT iv.prod_id, iv.cust_id, SUM(iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM products, sales WHERE sales.prod_id = products.prod.id) IV GROUP BY iv.prod_id, iv.cust_id; 1 2

410 Copyright © 2007, Oracle. All rights reserved. F Transforming and Rewriting the Query from the Two Previous Examples -- Both above queries are finally re-written as follows: SELECT p_id, c_id, sum_sold FROM SUM_SALES_MV; -- Both above queries are first transformed as follows: SELECT prod_id, cust_id, sum(amount_sold) FROM MV_IV GROUP BY prod_id, cust_id; SELECT iv.prod_id, iv.cust_id, SUM(iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM products, sales WHERE sales.prod_id = products.prod.id) IV GROUP BY iv.prod_id, iv.cust_id; SELECT iv.prod_id, iv.cust_id, SUM(iv.amount_sold) sum_amount_sold FROM (SELECT prod_id, cust_id, amount_sold FROM sales, products WHERE sales.prod_id = products.prod.id) IV GROUP BY iv.prod_id, iv.cust_id;

411 Copyright © 2007, Oracle. All rights reserved. F Did Query Rewrite Occur? Execute the query Use the DBMS_MVIEW.EXPLAIN_ REWRITE procedure Was the query rewritten? Use the EXPLAIN PLAN statement

412 Copyright © 2007, Oracle. All rights reserved. F Query Rewrite Using Remote Tables in Oracle Database 11g Oracle supports query rewrite with MVs that reference tables at a single remote database site. The MV should be present at the site where the query is being issued. Because any remote table update cannot be propagated to the local site simultaneously, query rewrite will only work in the stale_tolerated mode. Whenever a query contains columns that are not found in the MV, a join back is used to rewrite the query. If the join back table is not found at the local site, query rewrite will not take place.

413 Copyright © 2007, Oracle. All rights reserved. F Query Rewrite Using Remote Tables: Example SELECT p.prod_id, t.week_ending_day, s.cust_id, SUM(s.amount_sold) AS sum_amount_sold FROM s, p, t WHERE s.time_id=t.time_id AND s.prod_id=p.prod_id GROUP BY p.prod_id, t.week_ending_day, s.cust_id; CREATE MATERIALIZED VIEW sum_sales_prod_week_mv ENABLE QUERY REWRITE AS SELECT p.prod_id, t.week_ending_day, s.cust_id, SUM(s.amount_sold) AS sum_amount_sold FROM p, t WHERE s.time_id=t.time_id AND s.prod_id=p.prod_id GROUP BY p.prod_id, t.week_ending_day, s.cust_id; SELECT prod_id, week_ending_day, cust_id, sum_amount_sold FROM sum_sales_prod_week_mv;

414 Copyright © 2007, Oracle. All rights reserved. F Summary In this lesson, you should have learned how to use: The materialized view enhancements: –List the new and updated MV catalog views –Describe the updated columns in the MV catalog views –Identify the refresh performance enhancements –Review the benefits of using materialized views The query rewrite enhancements: –Use the query rewrite enhancement to support queries with inline views –Identify the query rewrite enhancement that supports queries with remote tables


Download ppt "1 Copyright © 2007, Oracle. All rights reserved. Introducing the Oracle Database 11g SQL and PL/SQL New Features."

Similar presentations


Ads by Google