Sql and PL/SQL Best Practices I


Published on

In this first of a series of presentations, we'll overview the differences between SQL and PL/SQL, and the first steps in optimization, as understanding RULE vs. COST, and how to slash 90% response time in data extractions running in SQL*Plus.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Sql and PL/SQL Best Practices I

  1. 1. Carlos Oliveira / May 31, 2012
  2. 2. Agenda Oracle Database Overview  Introduction  What isSQL & PL/SQL  Performance X Organization  What is an Access Plan  Access Plan  Rules  Cost  Our Environment Parameters  How to use Cost  Improve Performance in SQL*Plus  POC  Training & Reference  Questions
  3. 3. IntroductionI am a forward-looking Information Systems Architect with asolid Oracle DBA background comprising the dailyinfrastructure tasks of the DBA, several projects as a DataModeler, and performance management projects.I Started on the mainframe business, and soon had a deep divein application development for Oracle databases. Afteracquiring an Oracle certification, I worked on performanceenhancement for applications using Oracle databases, and laterworked several years as an infrastructure DBA, later I workedon data modeling projects and more recently a performancemanagement project, on both application and database layers.
  4. 4. “The limits of my languagemean the limits of my world.”Ludwig Wittgenstein
  5. 5. What is SQL & PL/SQL•SQL - Is a data oriented language for selecting and manipulating sets ofdata.•It has to be parsed and transformed by the database into an execution planof how to access the data•The execution plan can be different due to environment changes•PL/SQL is a procedural language to create applications.•It is already a series of statements and commands to be executed by thedatabase•The program flow doesnt change, no matter the changes in theenvironment.
  6. 6. Performance X Organization PERFORMANCE ORGANIZATIONSQL •Faster access to data •Easier to understand the access plan •Faster retrieval of data •Easier to maintain the queryPL/SQL •Faster execution of the program •Easier to read the code •Less memory used •Easier to maintain the program
  7. 7. What is an Access PlanIt is created by Oracle optimizer for SELECT, UPDATE, INSERT, and DELETE statements.A statements execution plan is the sequence of operations Oracle performs to run the statement.The row source tree is the core of the execution plan. It shows the following information:•An ordering of the tables referenced by the statement•An access method for each table mentioned in the statement•A join method for tables affected by join operations in the statement•Data operations like filter, sort, or aggregationIn addition to the row source tree, the plan table contains information about the following:•Optimization, such as the cost and cardinality of each operation•Partitioning, such as the set of accessed partitions•Parallel execution, such as the distribution method of join inputsThe ACCESS PLAN results let you determine whether the optimizer selects a particular executionplan, such as, nested loops join. It also helps you to understand the optimizer decisions, such as why theoptimizer chose a nested loops join instead of a hash join, and lets you understand the performance of aquery.
  8. 8. Access PlanSELECT e.employee_id, j.job_title, e.salary, d.department_name FROM employees e, jobs j, departments d WHERE e.employee_id < 103 AND e.job_id = j.job_id AND e.department_id = d.department_id;-----------------------------------------------------------------------------------| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|-----------------------------------------------------------------------------------| 0 | SELECT STATEMENT | | 3 | 189 | 10 (10)|| 1 | NESTED LOOPS | | 3 | 189 | 10 (10)|| 2 | NESTED LOOPS | | 3 | 141 | 7 (15)||* 3 | TABLE ACCESS FULL | EMPLOYEES | 3 | 60 | 4 (25)|| 4 | TABLE ACCESS BY INDEX ROWID| JOBS | 19 | 513 | 2 (50)||* 5 | INDEX UNIQUE SCAN | JOB_ID_PK | 1 | | || 6 | TABLE ACCESS BY INDEX ROWID | DEPARTMENTS | 27 | 432 | 2 (50)||* 7 | INDEX UNIQUE SCAN | DEPT_ID_PK | 1 | | |-----------------------------------------------------------------------------------Predicate Information (identified by operation id):--------------------------------------------------- 3 - filter("E"."EMPLOYEE_ID"<103) 5 - access("E"."JOB_ID"="J"."JOB_ID") 7 - access("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
  9. 9. Access Plan
  10. 10. What Influences the Access PlanCOSTDifferent Costs Data volume and statistics Bind variable typesRULE•Order of the tables in the FROM clause•Order of the join conditions in the WHERE/JOIN clause•Collected Statistics•RulesGENERAL•Different Schemas/Databases/Users•Schema changes (usually changes in indexes) between the two operations.•Initialization parameters - set globally or at session level•Hints•Indexed Columns inhibitors (+0 or || )
  11. 11. Rules•RBO Path 1: Single Row by Rowid•RBO Path 2: Single Row by Cluster Join•RBO Path 3: Single Row by Hash Cluster Key with Unique or Primary Key•RBO Path 4: Single Row by Unique or Primary Key•RBO Path 5: Clustered Join•RBO Path 6: Hash Cluster Key•RBO Path 7: Indexed Cluster Key•RBO Path 8: Composite Index•RBO Path 9: Single-Column Indexes•RBO Path 10: Bounded Range Search on Indexed Columns•RBO Path 11: Unbounded Range Search on Indexed Columns•RBO Path 12: Sort Merge Join•RBO Path 13: MAX or MIN of Indexed Column•RBO Path 14: ORDER BY on Indexed Column•RBO Path 15: Full Table Scan
  12. 12. Cost Query Transformer Four different query transformation techniques: •View Merging •Predicate Pushing •Subquery Unnesting •Query Rewrite with Materialized Views Estimator Three different types of measures: •Selectivity •Cardinality •Cost Plan Generator
  13. 13. Sample Environment Parameters Database Version = Compatible = Optimizer Features Enable = 9.2.0 Optimizer Mode = CHOOSE Database Triggers => No (on_logon)
  14. 14. How to use Cost•Gather index StatisticsBEGIN •Set for session in SQL*PLUS SYS.DBMS_STATS.GATHER_INDEX_STATS ( ALTER SESSION SET OPTIMIZER_MODE=ALL_ROWS; OwnName => ‘HR ,IndName => IDX_JOB_3 •Use Hint /*+ ALL_ROWS */ ,Estimate_Percent => NULL Remove indexed columns inhibitors (+0 or || ) ,Degree => NULL ,No_Invalidate => FALSE); SELECT /*+ ALL_ROWS */ column1, column2, ...END;/ •Show Access Plan & Statistics in SQL*PLUS•Set for session in a program SET AUTOTRACE ON EXPLAIN STATISTICS;BEGIN EXECUTE_IMMEDIATE(‘ALTER SESSION SET OPTIMIZER_MODE = ALL_ROWS’); •Study the Access PlanEND;/
  15. 15. Improve Performance in SQL*PlusSYSTEM Variables Influencing SQL*Plus PerformanceSET ARRAYSIZESets the number of rows, called a batch, that SQL*Plus will fetch from the database at one time. Valid values are 1 to 5000. A large value increases theefficiency of queries and subqueries that fetch many rows, but requires more memory. Values over approximately 100 provide little added performance.ARRAYSIZE has no effect on the results of SQL*Plus operations other than increasing efficiency.SET DEFINE OFFControls whether SQL*Plus parses scripts for substitution variables. If DEFINE is OFF, SQL*Plus does not parse scripts for substitution variables. If yourscript does not use substitution variables, setting DEFINE OFF may result in some performance gains.SET FLUSH OFFControls when output is sent to the users display device. OFF allows the host operating system to buffer output which may improve performance byreducing the amount of program input and output.Use OFF only when you run a script that does not require user interaction and whose output you do not need to see until the script finishes running.SET SERVEROUTPUTControls whether SQL*Plus checks for and displays DBMS output. If SERVEROUTPUT is OFF, SQL*Plus does not check for DBMS output and does notdisplay output after applicable SQL or PL/SQL statements. Suppressing this output checking and display may result in performance gains.SET TRIMOUT ONDetermines whether SQL*Plus allows trailing blanks at the end of each displayed line. ON removes blanks at the end of each line, which may improveperformance especially when you access SQL*Plus from a slow communications device. TRIMOUT ON does not affect spooled output.SET TRIMSPOOL ONDetermines whether SQL*Plus allows trailing blanks at the end of each spooled line. ON removes blanks at the end of each line, which may improveperformance especially when you access SQL*Plus from a slow communications device. TRIMSPOOL ON does not affect terminal output.
  17. 17. POCWITHOUT PERFORMANCE PARAMETERS USING PERFORMANCE PARAMETERSdbtest> SET PAGESIZE 9999 dbtest> SET PAGESIZE 9999dbtest> SET TIMI ON; dbtest> --Improve performance and control in SQL*Plusdbtest> SELECT USERNAME FROM DBA_USERS; dbtest> ALTER SESSION SET optimizer_mode=ALL_ROWS;USERNAME Session altered.------------------------------ Elapsed: 00:00:00.48... dbtest> SET DEFINE OFF... dbtest> SET FLUSH OFF... dbtest> SET SERVEROUTPUT OFF dbtest> SET TRIMOUT ON41632 rows selected. dbtest> SET TRIMSPOOL ONElapsed: 00:22:28.75 dbtest> SET ARRAYSIZE 5000dbtest> SPOOL OFF; dbtest> SET TIMI ON; dbtest> PROMPT SETA DBMS_APPLICATION_INFO.SET_MODULE SETA DBMS_APPLICATION_INFO.SET_MODULE dbtest> BEGIN 2 DBMS_APPLICATION_INFO.SET_MODULE(XXXXXXXXX,); 3 END; 4 / PL/SQL procedure successfully completed. Elapsed: 00:00:00.48 dbtest> SELECT USERNAME FROM DBA_USERS; USERNAME ------------------------------ .... .... 41632 rows selected. Elapsed: 00:00:27.07 dbtest> SPOOL OFF;
  18. 18. Training & ReferenceResources at Oracle Website•Performance Tuning Guide and Referencehttp://docs.oracle.com/cd/B10500_01/server.920/a96533/toc.htm•SQL Referencehttp://docs.oracle.com/cd/B10500_01/server.920/a96540/toc.htm•PL/SQL Users Guide and Referencehttp://docs.oracle.com/cd/B10500_01/appdev.920/a96624/toc.htm
  19. 19. Thank youCarlos Oliveira / May 31, 2012