SlideShare a Scribd company logo
Carlos Oliveira / May 31, 2012
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
Introduction
I am a forward-looking Information Systems Architect with a
solid Oracle DBA background comprising the daily
infrastructure tasks of the DBA, several projects as a Data
Modeler, and performance management projects.

I Started on the mainframe business, and soon had a deep dive
in application development for Oracle databases. After
acquiring an Oracle certification, I worked on performance
enhancement for applications using Oracle databases, and later
worked several years as an infrastructure DBA, later I worked
on data modeling projects and more recently a performance
management project, on both application and database layers.
“The limits of my language
mean the limits of my world.”



Ludwig Wittgenstein
What is SQL & PL/SQL
•SQL - Is a data oriented language for selecting and manipulating sets of
data.
•It has to be parsed and transformed by the database into an execution plan
of 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 the
database
•The program flow doesn't change, no matter the changes in the
environment.
Performance X Organization
         PERFORMANCE                      ORGANIZATION
SQL      •Faster access to data           •Easier to understand the access plan
         •Faster retrieval of data        •Easier to maintain the query
PL/SQL   •Faster execution of the program •Easier to read the code
         •Less memory used                •Easier to maintain the program
What is an Access Plan
It is created by Oracle optimizer for SELECT, UPDATE, INSERT, and DELETE statements.
A statement's 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 aggregation

In 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 inputs

The ACCESS PLAN results let you determine whether the optimizer selects a particular execution
plan, such as, nested loops join. It also helps you to understand the optimizer decisions, such as why the
optimizer chose a nested loops join instead of a hash join, and lets you understand the performance of a
query.
Access Plan
SELECT 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")
Access Plan
What Influences the Access Plan
COST
Different Costs
     Data volume and statistics
     Bind variable types
RULE
•Order of the tables in the FROM clause
•Order of the join conditions in the WHERE/JOIN clause
•Collected Statistics
•Rules

GENERAL
•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 ||'' )
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
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
Sample Environment Parameters
 Database Version = 9.2.0.8.0

 Compatible = 9.2.0.0.0

 Optimizer Features Enable = 9.2.0

 Optimizer Mode = CHOOSE

 Database Triggers => No (on_logon)
How to use Cost
•Gather index Statistics
BEGIN                                                                   •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 Plan
END;
/
Improve Performance in SQL*Plus
SYSTEM Variables Influencing SQL*Plus Performance
SET ARRAYSIZE
Sets 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 the
efficiency 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 OFF
Controls whether SQL*Plus parses scripts for substitution variables. If DEFINE is OFF, SQL*Plus does not parse scripts for substitution variables. If your
script does not use substitution variables, setting DEFINE OFF may result in some performance gains.
SET FLUSH OFF
Controls when output is sent to the user's display device. OFF allows the host operating system to buffer output which may improve performance by
reducing 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 SERVEROUTPUT
Controls whether SQL*Plus checks for and displays DBMS output. If SERVEROUTPUT is OFF, SQL*Plus does not check for DBMS output and does not
display output after applicable SQL or PL/SQL statements. Suppressing this output checking and display may result in performance gains.
SET TRIMOUT ON
Determines whether SQL*Plus allows trailing blanks at the end of each displayed line. ON removes blanks at the end of each line, which may improve
performance especially when you access SQL*Plus from a slow communications device. TRIMOUT ON does not affect spooled output.
SET TRIMSPOOL ON
Determines whether SQL*Plus allows trailing blanks at the end of each spooled line. ON removes blanks at the end of each line, which may improve
performance especially when you access SQL*Plus from a slow communications device. TRIMSPOOL ON does not affect terminal output.
Improve Performance in SQL*Plus
•Improve performance and control in SQL*Plus
ALTER SESSION SET optimizer_mode=ALL_ROWS;
SET DEFINE OFF
SET FLUSH OFF
SET SERVEROUTPUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
-- ARRAYSIZE DEFAULT = 15
SET ARRAYSIZE 5000
SET TIMI ON;


PROMPT SETA DBMS_APPLICATION_INFO.SET_MODULE
BEGIN
    DBMS_APPLICATION_INFO.SET_MODULE(‘XXXXXXXXX','');
END;
/
POC
WITHOUT PERFORMANCE PARAMETERS                 USING PERFORMANCE PARAMETERS
dbtest> SET PAGESIZE 9999                  dbtest> SET PAGESIZE 9999
dbtest> SET TIMI ON;                       dbtest> --Improve performance and control in SQL*Plus
dbtest> 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 ON
41632 rows selected.                       dbtest> SET TRIMSPOOL ON
Elapsed: 00:22:28.75                       dbtest> SET ARRAYSIZE 5000
dbtest> 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;
Training & Reference
Resources at Oracle Website
•Performance Tuning Guide and Reference
http://docs.oracle.com/cd/B10500_01/server.920/a96533/toc.htm

•SQL Reference
http://docs.oracle.com/cd/B10500_01/server.920/a96540/toc.htm

•PL/SQL User's Guide and Reference
http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/toc.htm
Thank you




Carlos Oliveira / May 31, 2012

More Related Content

PDF
Indexing Strategies for Oracle Databases - Beyond the Create Index Statement
PPT
Oracle query optimizer
PPT
Do You Know The 11g Plan?
TXT
Oracle sql tuning
PPTX
Oracle Database 12c - Data Redaction
PPT
Top 10 Oracle SQL tuning tips
PDF
Online Statistics Gathering for ETL
PPTX
Adaptive Query Optimization in 12c
Indexing Strategies for Oracle Databases - Beyond the Create Index Statement
Oracle query optimizer
Do You Know The 11g Plan?
Oracle sql tuning
Oracle Database 12c - Data Redaction
Top 10 Oracle SQL tuning tips
Online Statistics Gathering for ETL
Adaptive Query Optimization in 12c

What's hot (20)

PDF
SQL Macros - Game Changing Feature for SQL Developers?
PPTX
Optimizing MySQL Queries
PDF
Oracle Database In-Memory and the Query Optimizer
PDF
Flashback - The Time Machine..
PPTX
Oracle database performance tuning
PPT
Oracle-L11 using Oracle flashback technology-Mazenet solution
PPT
Explain that explain
PPTX
Oracle 12c SPM
PPT
12c Database new features
PDF
MERGE SQL Statement: Lesser Known Facets
PDF
Oracle SQL Tuning
PDF
How to analyze and tune sql queries for better performance percona15
PDF
DB2 LUW Access Plan Stability
PDF
2011 Collaborate IOUG Presentation
PPTX
Oracle flashback
PDF
Oracle Diagnostics : Joins - 1
PPTX
Indexes: Structure, Splits and Free Space Management Internals
PDF
Properly Use Parallel DML for ETL
PPTX
Oracle Database Performance Tuning Basics
PPTX
Advanced functions in PL SQL
SQL Macros - Game Changing Feature for SQL Developers?
Optimizing MySQL Queries
Oracle Database In-Memory and the Query Optimizer
Flashback - The Time Machine..
Oracle database performance tuning
Oracle-L11 using Oracle flashback technology-Mazenet solution
Explain that explain
Oracle 12c SPM
12c Database new features
MERGE SQL Statement: Lesser Known Facets
Oracle SQL Tuning
How to analyze and tune sql queries for better performance percona15
DB2 LUW Access Plan Stability
2011 Collaborate IOUG Presentation
Oracle flashback
Oracle Diagnostics : Joins - 1
Indexes: Structure, Splits and Free Space Management Internals
Properly Use Parallel DML for ETL
Oracle Database Performance Tuning Basics
Advanced functions in PL SQL
Ad

Viewers also liked (7)

PPTX
Le Top 10 des Best Practices pour SQL Server
PDF
KM 101
PDF
Challenger Banks in Europe: Challenge Accepted
PPTX
SQL Server 2012 Best Practices
PDF
The Irish Tech Startup Guide
PDF
Social Network Analysis & an Introduction to Tools
PDF
The Buyer's Journey - by Chris Lema
Le Top 10 des Best Practices pour SQL Server
KM 101
Challenger Banks in Europe: Challenge Accepted
SQL Server 2012 Best Practices
The Irish Tech Startup Guide
Social Network Analysis & an Introduction to Tools
The Buyer's Journey - by Chris Lema
Ad

Similar to Sql and PL/SQL Best Practices I (20)

PPTX
Top 10 tips for Oracle performance
PPTX
Oracle sql high performance tuning
PPTX
Oracle performance tuning for java developers
ODP
SQL Tunning
PDF
Managing Statistics for Optimal Query Performance
PPTX
MySQL Optimizer Overview
PDF
Hailey_Database_Performance_Made_Easy_through_Graphics.pdf
PDF
Shaping Optimizer's Search Space
PPTX
Presentación Oracle Database Migración consideraciones 10g/11g/12c
PDF
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
PDF
Presentation interpreting execution plans for sql statements
PPTX
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
PDF
Brad McGehee Intepreting Execution Plans Mar09
PDF
Brad McGehee Intepreting Execution Plans Mar09
PPTX
MySQL Optimizer Overview
PPT
Myth busters - performance tuning 101 2007
PPTX
Part3 Explain the Explain Plan
PPTX
02 database oprimization - improving sql performance - ent-db
PDF
Oracle SQL tuning with SQL Plan Management
PDF
Oracle Query Tuning Tips - Get it Right the First Time
Top 10 tips for Oracle performance
Oracle sql high performance tuning
Oracle performance tuning for java developers
SQL Tunning
Managing Statistics for Optimal Query Performance
MySQL Optimizer Overview
Hailey_Database_Performance_Made_Easy_through_Graphics.pdf
Shaping Optimizer's Search Space
Presentación Oracle Database Migración consideraciones 10g/11g/12c
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
Presentation interpreting execution plans for sql statements
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
MySQL Optimizer Overview
Myth busters - performance tuning 101 2007
Part3 Explain the Explain Plan
02 database oprimization - improving sql performance - ent-db
Oracle SQL tuning with SQL Plan Management
Oracle Query Tuning Tips - Get it Right the First Time

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
cuic standard and advanced reporting.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Big Data Technologies - Introduction.pptx
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
cuic standard and advanced reporting.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Chapter 3 Spatial Domain Image Processing.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Review of recent advances in non-invasive hemoglobin estimation
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Spectral efficient network and resource selection model in 5G networks
Big Data Technologies - Introduction.pptx
GamePlan Trading System Review: Professional Trader's Honest Take
Empathic Computing: Creating Shared Understanding

Sql and PL/SQL Best Practices I

  • 1. Carlos Oliveira / May 31, 2012
  • 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. Introduction I am a forward-looking Information Systems Architect with a solid Oracle DBA background comprising the daily infrastructure tasks of the DBA, several projects as a Data Modeler, and performance management projects. I Started on the mainframe business, and soon had a deep dive in application development for Oracle databases. After acquiring an Oracle certification, I worked on performance enhancement for applications using Oracle databases, and later worked several years as an infrastructure DBA, later I worked on data modeling projects and more recently a performance management project, on both application and database layers.
  • 4. “The limits of my language mean the limits of my world.” Ludwig Wittgenstein
  • 5. What is SQL & PL/SQL •SQL - Is a data oriented language for selecting and manipulating sets of data. •It has to be parsed and transformed by the database into an execution plan of 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 the database •The program flow doesn't change, no matter the changes in the environment.
  • 6. Performance X Organization PERFORMANCE ORGANIZATION SQL •Faster access to data •Easier to understand the access plan •Faster retrieval of data •Easier to maintain the query PL/SQL •Faster execution of the program •Easier to read the code •Less memory used •Easier to maintain the program
  • 7. What is an Access Plan It is created by Oracle optimizer for SELECT, UPDATE, INSERT, and DELETE statements. A statement's 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 aggregation In 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 inputs The ACCESS PLAN results let you determine whether the optimizer selects a particular execution plan, such as, nested loops join. It also helps you to understand the optimizer decisions, such as why the optimizer chose a nested loops join instead of a hash join, and lets you understand the performance of a query.
  • 8. Access Plan SELECT 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")
  • 10. What Influences the Access Plan COST Different Costs Data volume and statistics Bind variable types RULE •Order of the tables in the FROM clause •Order of the join conditions in the WHERE/JOIN clause •Collected Statistics •Rules GENERAL •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. 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. 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. Sample Environment Parameters Database Version = 9.2.0.8.0 Compatible = 9.2.0.0.0 Optimizer Features Enable = 9.2.0 Optimizer Mode = CHOOSE Database Triggers => No (on_logon)
  • 14. How to use Cost •Gather index Statistics BEGIN •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 Plan END; /
  • 15. Improve Performance in SQL*Plus SYSTEM Variables Influencing SQL*Plus Performance SET ARRAYSIZE Sets 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 the efficiency 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 OFF Controls whether SQL*Plus parses scripts for substitution variables. If DEFINE is OFF, SQL*Plus does not parse scripts for substitution variables. If your script does not use substitution variables, setting DEFINE OFF may result in some performance gains. SET FLUSH OFF Controls when output is sent to the user's display device. OFF allows the host operating system to buffer output which may improve performance by reducing 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 SERVEROUTPUT Controls whether SQL*Plus checks for and displays DBMS output. If SERVEROUTPUT is OFF, SQL*Plus does not check for DBMS output and does not display output after applicable SQL or PL/SQL statements. Suppressing this output checking and display may result in performance gains. SET TRIMOUT ON Determines whether SQL*Plus allows trailing blanks at the end of each displayed line. ON removes blanks at the end of each line, which may improve performance especially when you access SQL*Plus from a slow communications device. TRIMOUT ON does not affect spooled output. SET TRIMSPOOL ON Determines whether SQL*Plus allows trailing blanks at the end of each spooled line. ON removes blanks at the end of each line, which may improve performance especially when you access SQL*Plus from a slow communications device. TRIMSPOOL ON does not affect terminal output.
  • 16. Improve Performance in SQL*Plus •Improve performance and control in SQL*Plus ALTER SESSION SET optimizer_mode=ALL_ROWS; SET DEFINE OFF SET FLUSH OFF SET SERVEROUTPUT OFF SET TRIMOUT ON SET TRIMSPOOL ON -- ARRAYSIZE DEFAULT = 15 SET ARRAYSIZE 5000 SET TIMI ON; PROMPT SETA DBMS_APPLICATION_INFO.SET_MODULE BEGIN DBMS_APPLICATION_INFO.SET_MODULE(‘XXXXXXXXX',''); END; /
  • 17. POC WITHOUT PERFORMANCE PARAMETERS USING PERFORMANCE PARAMETERS dbtest> SET PAGESIZE 9999 dbtest> SET PAGESIZE 9999 dbtest> SET TIMI ON; dbtest> --Improve performance and control in SQL*Plus dbtest> 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 ON 41632 rows selected. dbtest> SET TRIMSPOOL ON Elapsed: 00:22:28.75 dbtest> SET ARRAYSIZE 5000 dbtest> 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. Training & Reference Resources at Oracle Website •Performance Tuning Guide and Reference http://docs.oracle.com/cd/B10500_01/server.920/a96533/toc.htm •SQL Reference http://docs.oracle.com/cd/B10500_01/server.920/a96540/toc.htm •PL/SQL User's Guide and Reference http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/toc.htm
  • 19. Thank you Carlos Oliveira / May 31, 2012