SlideShare une entreprise Scribd logo
1  sur  66
Refactor	
  Mercilessly,	
  
    Index	
  Wisely	
  

          Karen	
  Morton	
  
  Sr.	
  Technical	
  Consultant	
  
karen.morton@enkitec.com	
  

karenmorton.blogspot.com	
  


karen_morton	
  
Topics	
  
•  Common	
  ways	
  to	
  rewrite	
  SQL	
  to	
  make	
  it	
  
   perform	
  beFer	
  and	
  more	
  consistently	
  
•  How	
  to	
  easily	
  idenHfy	
  &	
  test	
  your	
  SQL	
  
•  How	
  and	
  when	
  to	
  index	
  
    –  AddiHons	
  or	
  modificaHons	
  to	
  provide	
  best	
  soluHon	
  
    –  Best	
  choice	
  of	
  columns	
  and	
  in	
  what	
  order	
  
    –  Trade-­‐offs	
  for	
  determining	
  the	
  "best"	
  index	
  
RewriHng	
  
  SQL	
  
First	
  
                things	
  
                 first	
  
(This	
  stuff	
  is	
  really	
  important)	
  
Review	
  the	
  statement.	
  
	
  
What	
  is	
  it	
  	
  
       	
   	
   	
   	
  supposed	
  	
  
       	
   	
   	
   	
   	
   	
   	
   	
   	
  to	
  do?	
  
	
  
Collect	
  data.	
  
       	
  
Review	
  staHsHcs.	
  
            	
  
Check	
  
            indexes	
  	
  
                   and	
  	
  
	
  	
   	
  	
   	
  	
   	
  constraints.	
  
Execute	
  
the	
  query.	
  
Evaluate	
  
            the	
  plan.	
  
(compare	
  esHmates	
  to	
  actuals)	
  
Where	
  are	
  the	
  	
  
big	
  hiFers?	
  
       Time?	
  
   Resources?	
  
Refactor	
  
the	
  statement.	
  
   (if	
  you	
  should)	
  
Modify	
  or	
  Add	
  
indexes,	
  constraints,	
  staHsHcs.	
  
             (if	
  you	
  should)	
  
T	
  T	
  D	
  
(Test	
  To	
  DestrucHon)	
  
Iterate	
  
    unHl	
  target	
  met	
  or	
  no	
  
further	
  improvement	
  possible	
  
How	
  do	
  you	
  do	
  simple,	
  	
  
yet	
  effecHve,	
  tesHng?	
  
Name	
  your	
  SQL	
  

                      SELECT /* kmtest */ …
                      FROM   tab …


                      SELECT /*+ qb_name (sql42) */ …
                      FROM   tab …



Comments	
  stored	
  with	
  full	
  SQL	
  in	
  the	
  SQL_TEXT	
  column	
  in	
  v$sql,	
  v$sqltext,	
  dba_hist_sqltext.	
  
                                                                	
  
       QBLOCK_NAME	
  stored	
  in	
  v$sql_plan,	
  v$sql_plan_staHsHcs_all,	
  dba_hist_sql_plan.	
  
/*+	
  gather_plan_staHsHcs	
  */	
  
       (staHsHcs_level	
  =	
  ALL)	
  
dbms_xplan.display_cursor	
  
       ('ALLSTATS	
  LAST')	
  
SQL> select
          /* kmtest */
          /*+ gather_plan_statistics */
          count(*)
     from sales ;


Plan hash value: 1047182207

----------------------------------------------------------------------------------------------
| Id | Operation                   | Name | Starts | E-Rows | A-Rows |    A-Time   | Buffers |
----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |       |      1 |        |      1 |00:00:00.13 |    4440 |
|   1 | SORT AGGREGATE             |       |      1 |      1 |      1 |00:00:00.13 |    4440 |
|   2 |   TABLE ACCESS STORAGE FULL| SALES |      1 |    918K|    918K|00:00:00.08 |    4440 |
----------------------------------------------------------------------------------------------
/*+	
  monitor	
  */	
  
dbms_sqltune.report_sql_monitor	
  
      (TEXT,	
  HTML,	
  XML,	
  ACTIVE)	
  




       Monitored	
  statements	
  can	
  be	
  found	
  in	
  V$SQL_MONITOR	
  
SQL> select
          /* sql42 */
          /*+ monitor */
          count(*)
     from sales ;


Global Stats
=================================================
| Elapsed |   Cpu   | Other    | Fetch | Buffer |
| Time(s) | Time(s) | Waits(s) | Calls | Gets |
=================================================
|    0.03 |    0.03 |     0.00 |     1 |   4440 |
=================================================

SQL Plan Monitoring Details (Plan Hash Value=1047182207)
======================================================================================================
| Id |          Operation           | Name | Rows     | Cost |   Time    | Start | Execs |    Rows   |
|    |                              |       | (Estim) |      | Active(s) | Active |       | (Actual) |
======================================================================================================
| 0 | SELECT STATEMENT              |       |         |      |         1 |     +0 |     1 |        1 |
| 1 |    SORT AGGREGATE             |       |       1 |      |         1 |     +0 |     1 |        1 |
| 2 |     TABLE ACCESS STORAGE FULL | SALES |    919K | 1230 |         1 |     +0 |     1 |     919K |
======================================================================================================
@fsx kmtest!
!
!
col sql_id       new_value r_sqlid!
col child_number new_value r_childno!
!
!
SELECT /* NOVIEW */ !
  ! ! sql_id, child_number ...!
FROM   gv$sql s!
WHERE sql_text like '%&&1%'!
AND    sql_text not like '%NOVIEW%'!
AND    sql_text not like 'BEGIN :sql_%'!
ORDER BY 1 ;!
@dplan!
SELECT *!
FROM    table(dbms_xplan.display_cursor (!
 ! ! SQL_ID => '&r_sqlid', !
 ! ! CURSOR_CHILD_NO => NVL(&r_childno,0), !
 ! ! FORMAT => 'ALLSTATS LAST')) !
WHERE '&r_sqlid' IS NOT NULL ;!



@rsm!
SELECT   dbms_sqltune.report_sql_monitor(!
 ! !     SQL_ID => '&r_sqlid',!
 ! !     TYPE => 'HTML') !
FROM     dual!
WHERE    '&r_sqlid' IS NOT NULL ;!
How	
  do	
  you	
  know	
  when	
  
 refactoring	
  SQL	
  is	
  the	
  
      best	
  opHon?	
  
A	
  poor	
  execuHon	
  plan	
  
       is	
  consistently	
  	
  
         developed.	
  
Why	
  You	
  Should	
  Refactor	
  
•    You	
  know	
  your	
  stuff	
  best	
  (or	
  you	
  should)	
  
•    Always	
  filter	
  early	
  
•    Defines	
  your	
  expectaHons	
  
•    K.I.S.S.	
  
•    The	
  opHmizer	
  might	
  not	
  be	
  able	
  to	
  
Common	
  Refactoring	
  	
  
    SituaHons	
  
Look	
  for	
  	
  
"column-­‐less"	
  
joined	
  tables.	
  
This	
  

 SELECT       b.*
 FROM         a, b
 WHERE        a.col1 = b.col1
 AND          b.col2 = <condition>

Becomes	
  

 SELECT       b.*
 FROM         b
 WHERE        b.col2 = <condition>
 AND          EXISTS (SELECT null
 FROM a       WHERE a.col1 = b.col1)
Look	
  for	
  	
  
 improper	
  
outer	
  joins.	
  
This	
  

 AND tab1.col1 = tab2.col1 (+)
 AND tab2.col2 = <condition>


Becomes	
  

 AND tab1.col1 = tab2.col1
 AND tab2.col2 = <condition>


Because	
  the	
  condiHon	
  would	
  be	
  null	
  for	
  the	
  outer	
  joined	
  row,	
  	
  
so	
  the	
  predicate	
  could	
  never	
  be	
  true.	
  
Look	
  for	
  	
  
 repeated	
  use	
  
of	
  same	
  tables	
  
and	
  predicates.	
  
SELECT rite.event_name, count(*)
  FROM riffs.rf_order ro, riffs.rf_order_item roi,
       riffs.rf_item_transaction rit,
       riffs.rf_item_transaction_event rite
 WHERE ro.is_test = '0'
   AND ro.order_id = roi.order_id
   AND roi.order_item_id = rit.order_item_id
   AND roi.order_id = rit.order_id
   AND rit.transaction_id = rite.transaction_id
   AND (rite.event_name >'AUTHORIZED' OR rite.event_name <'AUTHORIZED')
 GROUP BY rite.event_name
UNION ALL
SELECT 'TRANSACTION_INITIATED', count(*)
  FROM
(SELECT count(*)
   FROM riffs.rf_order ro, riffs.rf_order_item roi,
        riffs.rf_item_transaction rit,
        riffs.rf_item_transaction_event rite
  WHERE ro.is_test = '0'
    AND ro.order_id = roi.order_id
    AND roi.order_item_id = rit.order_item_id
    AND roi.order_id = rit.order_id
    AND rit.transaction_id = rite.transaction_id
    AND rite.event_name = 'AUTHORIZED'
  GROUP BY substr(rit.TRANSACTION_ID,1,INSTR(rit.TRANSACTION_ID,'_')-1))
Look	
  for	
  	
  
 simple	
  predicates	
  
  ORed	
  with	
  other	
  
predicates	
  in	
  ranges.	
  
This	
  

             col1 > <condition>
 OR          col2 > <condition>


Becomes	
  

     col1 > <condition>
 UNION / UNION ALL
 AND col2 > <condition>
Because	
  a	
  row	
  could	
  not	
  be	
  rejected	
  when	
  one	
  predicate	
  is	
  false	
  
without	
  checking	
  the	
  other	
  predicates.	
  
Look	
  for	
  
   DISTINCT/UNION	
  
to	
  remove	
  duplicates.	
  

    Consider	
  using	
  IN	
  or	
  EXISTS	
  instead.	
  
Think	
  like	
  the	
  opHmizer.	
  
 Query	
  TransformaHon	
  
Simple	
  View	
  Merging	
  




                        is transformed into




Merged	
  automaHcally	
  as	
  it	
  is	
  deemed	
  “always	
  beFer”	
  	
  
    for	
  the	
  opHmizer	
  to	
  work	
  with	
  direct	
  joins.	
  
Complex	
  View	
  Merging	
  




                         is transformed into




                      “Complex”	
  due	
  to	
  GROUP	
  BY.	
  	
  
CVM	
  can	
  also	
  be	
  done	
  when	
  using	
  DISTINCT	
  or	
  outer	
  join.	
  
Filter	
  Push-­‐Down	
  



                                       is transformed into




Purpose:	
  To	
  push	
  outer	
  query	
  predicates	
  into	
  view	
  to	
  perform	
  earlier	
  filtering.	
  
Predicate	
  Move-­‐Around	
  



                                        is transformed into




Purpose:	
  To	
  move	
  inexpensive	
  predicates	
  into	
  view	
  query	
  blocks	
  to	
  perform	
  earlier	
  filtering.	
  
     Can	
  generate	
  filter	
  predicates	
  based	
  on	
  transiHvity	
  or	
  funcHonal	
  dependencies.	
  
Join	
  FactorizaHon	
  



                                         is transformed into




Combines	
  branches	
  of	
  UNION	
  /	
  UNION	
  ALL	
  that	
  join	
  a	
  common	
  table	
  in	
  order	
  to	
  
                              reduce	
  #	
  of	
  accesses	
  to	
  that	
  table.	
  
Understanding	
  how	
  the	
  
 opHmizer	
  transforms	
  queries	
  
helps	
  you	
  write	
  beFer	
  SQL	
  and	
  
 understand	
  execuHon	
  plans.	
  
How	
  and	
  When	
  
  to	
  Index	
  
For	
  many	
  years,	
  inadequate	
  indexing	
  
has	
  been	
  the	
  most	
  	
  common	
  cause	
  of	
  
performance	
  disappointments.	
  
	
  
                                 –	
   	
  Tapio	
  Lahdenmäki	
  
	
  
Indexing	
  Problems	
  
•  Indexes	
  that	
  do	
  not	
  have	
  sufficient	
  columns	
  to	
  
   support	
  all	
  predicates	
  
•  Not	
  enough	
  indexes	
  present	
  
    –  Numerous	
  single-­‐column	
  but	
  few	
  mulH-­‐column	
  
•  Indexes	
  with	
  the	
  right	
  columns	
  but	
  in	
  the	
  
   wrong	
  order	
  
How	
  many	
  is	
  
"too"	
  many?	
  
Heavy	
  DML?	
  
Large,	
  bulk	
  loads?	
  
           or	
  
  Mostly	
  query?	
  
Indexes	
  support	
  
query	
  performance	
  
Inadequate	
  Index	
  

SELECT !cust_id, cust_first_name!
FROM ! !customers!
    !
WHERE ! !cust_last_name = 'Ruddy'!
AND ! ! !cust_city = 'Ede'!
ORDER BY cust_first_name ;!



        Index	
  present	
  on	
  CUST_LAST_NAME,	
  CUST_FIRST_NAME	
  
                              #	
  rows	
  in	
  table	
  =	
  55,500	
  
Note	
  the	
  number	
  of	
  rows	
  that	
  are	
  thrown	
  away	
  in	
  step	
  1	
  (79).	
  
Index	
  on	
  CUST_LAST_NAME,	
  CUST_CITY	
  
                                 No	
  throwaway	
  




Index	
  on	
  CUST_CITY,	
  CUST_LAST_NAME,	
  CUST_FIRST_NAME,	
  CUST_ID	
  
                               No	
  throwaway,	
  no	
  sort	
  
Index	
  Design	
  Strategies	
  
Columns	
  from	
  all	
  equality	
  predicates	
  
in	
  any	
  order	
  
	
  




Add	
  columns	
  in	
  the	
  order	
  used	
  in	
  
ORDER	
  BY	
  
	
  




Add	
  all	
  remaining	
  columns	
  from	
  
column	
  list	
  in	
  any	
  order	
  
•  VolaHle	
  columns	
  at	
  end	
  (reduces	
  impact	
  on	
  
   updates)	
  
Range	
  predicates	
  
             are	
  usually	
  placed	
  ater	
  
              1	
  and	
  2	
  star	
  columns.	
  



               Range	
  predicates	
  mean	
  3-­‐star	
  indexes	
  aren't	
  possible.	
  
The	
  2nd	
  star	
  is	
  usually	
  sacrificed	
  in	
  preference	
  of	
  a	
  more	
  selecHve	
  index.	
  
A	
  3-­‐star	
  index	
  is	
  
 oten	
  called	
  a	
  
           fat
             	
  
          index.	
  	
  
An	
  index	
  that	
  contains	
  all	
  the	
  
      columns	
  referenced	
  in	
  
       the	
  WHERE	
  clause	
  is	
  a	
  	
  
               semi-fat	
  
                 index.	
  	
  

       If	
  no	
  semi-­‐fat	
  index	
  exists,	
  this	
  is	
  a	
  warning	
  flag	
  
                     for	
  possible	
  performance	
  issues.	
  
There	
  will	
  always	
  be	
  trade-­‐offs.	
  
                     	
  
   Test	
  alternaHves	
  or	
  use	
  
   "worst	
  case"	
  formula	
  to	
  
  esHmate	
  response	
  Hmes.	
  
                     	
  	
  
The	
  key	
  to	
  determining	
  an	
  ideal	
  index	
  
	
  	
  


              The	
  index	
  should	
  provide	
  
             adequate	
  enough	
  screening	
  
             to	
  minimize	
  table	
  accesses.	
  
                                	
  	
  
Recap	
  
•  Look	
  for	
  common	
  anH-­‐paFerns	
  in	
  SQL	
  
•  Gather	
  enough	
  diagnosHc	
  data	
  to	
  know	
  where	
  
     the	
  problem	
  originates	
  
•  Learn	
  what	
  the	
  opHmizer	
  expects	
  (and	
  give	
  it	
  
     what	
  it	
  wants!)	
  
•  Think	
  about	
  your	
  indexing	
  strategy	
  
•  Design	
  indexes	
  for	
  opHmal	
  coverage	
  to	
  limit	
  
     table	
  accesses	
  
	
  
	
  
Q	
  &	
  A	
  
Thank	
  you!	
  

Contenu connexe

Tendances

Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
Oracle 11g PL/SQL notes
Oracle 11g PL/SQL notesOracle 11g PL/SQL notes
Oracle 11g PL/SQL notesanilakduygu
 
MariaDB Optimizer - further down the rabbit hole
MariaDB Optimizer - further down the rabbit holeMariaDB Optimizer - further down the rabbit hole
MariaDB Optimizer - further down the rabbit holeSergey Petrunya
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Advanced functions in PL SQL
Advanced functions in PL SQLAdvanced functions in PL SQL
Advanced functions in PL SQLHosein Zare
 
Histograms: Pre-12c and now
Histograms: Pre-12c and nowHistograms: Pre-12c and now
Histograms: Pre-12c and nowAnju Garg
 
Explaining the Postgres Query Optimizer
Explaining the Postgres Query OptimizerExplaining the Postgres Query Optimizer
Explaining the Postgres Query OptimizerEDB
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?Andrej Pashchenko
 
Firebird 3 Windows Functions
Firebird 3 Windows  FunctionsFirebird 3 Windows  Functions
Firebird 3 Windows FunctionsMind The Firebird
 
Adaptive Query Optimization in 12c
Adaptive Query Optimization in 12cAdaptive Query Optimization in 12c
Adaptive Query Optimization in 12cAnju Garg
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performanceSergey Petrunya
 
Boost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitionsBoost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitionsGiuseppe Maxia
 
Optimizer features in recent releases of other databases
Optimizer features in recent releases of other databasesOptimizer features in recent releases of other databases
Optimizer features in recent releases of other databasesSergey Petrunya
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsAndrej Pashchenko
 

Tendances (19)

Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
Oracle 11g caracteristicas poco documentadas 3 en 1
Oracle 11g caracteristicas poco documentadas 3 en 1Oracle 11g caracteristicas poco documentadas 3 en 1
Oracle 11g caracteristicas poco documentadas 3 en 1
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Sql
SqlSql
Sql
 
Oracle 11g PL/SQL notes
Oracle 11g PL/SQL notesOracle 11g PL/SQL notes
Oracle 11g PL/SQL notes
 
MariaDB Optimizer - further down the rabbit hole
MariaDB Optimizer - further down the rabbit holeMariaDB Optimizer - further down the rabbit hole
MariaDB Optimizer - further down the rabbit hole
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Advanced functions in PL SQL
Advanced functions in PL SQLAdvanced functions in PL SQL
Advanced functions in PL SQL
 
Histograms: Pre-12c and now
Histograms: Pre-12c and nowHistograms: Pre-12c and now
Histograms: Pre-12c and now
 
Oracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guideOracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guide
 
Explaining the Postgres Query Optimizer
Explaining the Postgres Query OptimizerExplaining the Postgres Query Optimizer
Explaining the Postgres Query Optimizer
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?
 
Firebird 3 Windows Functions
Firebird 3 Windows  FunctionsFirebird 3 Windows  Functions
Firebird 3 Windows Functions
 
Adaptive Query Optimization in 12c
Adaptive Query Optimization in 12cAdaptive Query Optimization in 12c
Adaptive Query Optimization in 12c
 
Using histograms to get better performance
Using histograms to get better performanceUsing histograms to get better performance
Using histograms to get better performance
 
Boost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitionsBoost performance with MySQL 5.1 partitions
Boost performance with MySQL 5.1 partitions
 
Optimizer features in recent releases of other databases
Optimizer features in recent releases of other databasesOptimizer features in recent releases of other databases
Optimizer features in recent releases of other databases
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
 

Similaire à SQL Performance Solutions: Refactor Mercilessly, Index Wisely

Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdfNOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdfcookie1969
 
Performance tuning
Performance tuningPerformance tuning
Performance tuningami111
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ICarlos Oliveira
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planMaria Colgan
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_planarief12H
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsNirav Shah
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain PlanMaria Colgan
 
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMB
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMBADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMB
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMBLudovico Caldara
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_planMaria Colgan
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
SQL Optimization With Trace Data And Dbms Xplan V6
SQL Optimization With Trace Data And Dbms Xplan V6SQL Optimization With Trace Data And Dbms Xplan V6
SQL Optimization With Trace Data And Dbms Xplan V6Mahesh Vallampati
 
Writing efficient sql
Writing efficient sqlWriting efficient sql
Writing efficient sqlj9soto
 
Optimizing applications and database performance
Optimizing applications and database performanceOptimizing applications and database performance
Optimizing applications and database performanceInam Bukhary
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Traceoysteing
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Alex Zaballa
 
Top 10 tips for Oracle performance
Top 10 tips for Oracle performanceTop 10 tips for Oracle performance
Top 10 tips for Oracle performanceGuy Harrison
 

Similaire à SQL Performance Solutions: Refactor Mercilessly, Index Wisely (20)

Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdfNOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
Sql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices ISql and PL/SQL Best Practices I
Sql and PL/SQL Best Practices I
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_plan
 
Explaining the explain_plan
Explaining the explain_planExplaining the explain_plan
Explaining the explain_plan
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
 
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMB
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMBADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMB
ADAPTIVE FEATURES OR: HOW I LEARNED TO STOP WORRYING AND TROUBLESHOOT THE BOMB
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_plan
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
SQL Optimization With Trace Data And Dbms Xplan V6
SQL Optimization With Trace Data And Dbms Xplan V6SQL Optimization With Trace Data And Dbms Xplan V6
SQL Optimization With Trace Data And Dbms Xplan V6
 
Writing efficient sql
Writing efficient sqlWriting efficient sql
Writing efficient sql
 
Optimizing applications and database performance
Optimizing applications and database performanceOptimizing applications and database performance
Optimizing applications and database performance
 
The MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer TraceThe MySQL Query Optimizer Explained Through Optimizer Trace
The MySQL Query Optimizer Explained Through Optimizer Trace
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
 
Top 10 tips for Oracle performance
Top 10 tips for Oracle performanceTop 10 tips for Oracle performance
Top 10 tips for Oracle performance
 

Plus de Enkitec

Using Angular JS in APEX
Using Angular JS in APEXUsing Angular JS in APEX
Using Angular JS in APEXEnkitec
 
Controlling execution plans 2014
Controlling execution plans   2014Controlling execution plans   2014
Controlling execution plans 2014Enkitec
 
Engineered Systems: Environment-as-a-Service Demonstration
Engineered Systems: Environment-as-a-Service DemonstrationEngineered Systems: Environment-as-a-Service Demonstration
Engineered Systems: Environment-as-a-Service DemonstrationEnkitec
 
Think Exa!
Think Exa!Think Exa!
Think Exa!Enkitec
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneEnkitec
 
In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1Enkitec
 
Mini Session - Using GDB for Profiling
Mini Session - Using GDB for ProfilingMini Session - Using GDB for Profiling
Mini Session - Using GDB for ProfilingEnkitec
 
Profiling Oracle with GDB
Profiling Oracle with GDBProfiling Oracle with GDB
Profiling Oracle with GDBEnkitec
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the TradeOracle Performance Tools of the Trade
Oracle Performance Tools of the TradeEnkitec
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsEnkitec
 
SQL Tuning Tools of the Trade
SQL Tuning Tools of the TradeSQL Tuning Tools of the Trade
SQL Tuning Tools of the TradeEnkitec
 
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan StabilityUsing SQL Plan Management (SPM) to Balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan StabilityEnkitec
 
Oracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture PerformanceOracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture PerformanceEnkitec
 
OGG Architecture Performance
OGG Architecture PerformanceOGG Architecture Performance
OGG Architecture PerformanceEnkitec
 
APEX Security Primer
APEX Security PrimerAPEX Security Primer
APEX Security PrimerEnkitec
 
How Many Ways Can I Manage Oracle GoldenGate?
How Many Ways Can I Manage Oracle GoldenGate?How Many Ways Can I Manage Oracle GoldenGate?
How Many Ways Can I Manage Oracle GoldenGate?Enkitec
 
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...Understanding how is that adaptive cursor sharing (acs) produces multiple opt...
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...Enkitec
 
Sql tuning made easier with sqltxplain (sqlt)
Sql tuning made easier with sqltxplain (sqlt)Sql tuning made easier with sqltxplain (sqlt)
Sql tuning made easier with sqltxplain (sqlt)Enkitec
 
Profiling the logwriter and database writer
Profiling the logwriter and database writerProfiling the logwriter and database writer
Profiling the logwriter and database writerEnkitec
 
Fatkulin hotsos 2014
Fatkulin hotsos 2014Fatkulin hotsos 2014
Fatkulin hotsos 2014Enkitec
 

Plus de Enkitec (20)

Using Angular JS in APEX
Using Angular JS in APEXUsing Angular JS in APEX
Using Angular JS in APEX
 
Controlling execution plans 2014
Controlling execution plans   2014Controlling execution plans   2014
Controlling execution plans 2014
 
Engineered Systems: Environment-as-a-Service Demonstration
Engineered Systems: Environment-as-a-Service DemonstrationEngineered Systems: Environment-as-a-Service Demonstration
Engineered Systems: Environment-as-a-Service Demonstration
 
Think Exa!
Think Exa!Think Exa!
Think Exa!
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry Osborne
 
In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1
 
Mini Session - Using GDB for Profiling
Mini Session - Using GDB for ProfilingMini Session - Using GDB for Profiling
Mini Session - Using GDB for Profiling
 
Profiling Oracle with GDB
Profiling Oracle with GDBProfiling Oracle with GDB
Profiling Oracle with GDB
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the TradeOracle Performance Tools of the Trade
Oracle Performance Tools of the Trade
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
SQL Tuning Tools of the Trade
SQL Tuning Tools of the TradeSQL Tuning Tools of the Trade
SQL Tuning Tools of the Trade
 
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan StabilityUsing SQL Plan Management (SPM) to Balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to Balance Plan Flexibility and Plan Stability
 
Oracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture PerformanceOracle GoldenGate Architecture Performance
Oracle GoldenGate Architecture Performance
 
OGG Architecture Performance
OGG Architecture PerformanceOGG Architecture Performance
OGG Architecture Performance
 
APEX Security Primer
APEX Security PrimerAPEX Security Primer
APEX Security Primer
 
How Many Ways Can I Manage Oracle GoldenGate?
How Many Ways Can I Manage Oracle GoldenGate?How Many Ways Can I Manage Oracle GoldenGate?
How Many Ways Can I Manage Oracle GoldenGate?
 
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...Understanding how is that adaptive cursor sharing (acs) produces multiple opt...
Understanding how is that adaptive cursor sharing (acs) produces multiple opt...
 
Sql tuning made easier with sqltxplain (sqlt)
Sql tuning made easier with sqltxplain (sqlt)Sql tuning made easier with sqltxplain (sqlt)
Sql tuning made easier with sqltxplain (sqlt)
 
Profiling the logwriter and database writer
Profiling the logwriter and database writerProfiling the logwriter and database writer
Profiling the logwriter and database writer
 
Fatkulin hotsos 2014
Fatkulin hotsos 2014Fatkulin hotsos 2014
Fatkulin hotsos 2014
 

Dernier

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Dernier (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

SQL Performance Solutions: Refactor Mercilessly, Index Wisely

  • 1. Refactor  Mercilessly,   Index  Wisely   Karen  Morton   Sr.  Technical  Consultant  
  • 3. Topics   •  Common  ways  to  rewrite  SQL  to  make  it   perform  beFer  and  more  consistently   •  How  to  easily  idenHfy  &  test  your  SQL   •  How  and  when  to  index   –  AddiHons  or  modificaHons  to  provide  best  soluHon   –  Best  choice  of  columns  and  in  what  order   –  Trade-­‐offs  for  determining  the  "best"  index  
  • 4. RewriHng   SQL  
  • 5.
  • 6. First   things   first   (This  stuff  is  really  important)  
  • 8. What  is  it            supposed                      to  do?    
  • 11. Check   indexes     and                  constraints.  
  • 13. Evaluate   the  plan.   (compare  esHmates  to  actuals)  
  • 14. Where  are  the     big  hiFers?   Time?   Resources?  
  • 15. Refactor   the  statement.   (if  you  should)  
  • 16. Modify  or  Add   indexes,  constraints,  staHsHcs.   (if  you  should)  
  • 17. T  T  D   (Test  To  DestrucHon)  
  • 18. Iterate   unHl  target  met  or  no   further  improvement  possible  
  • 19. How  do  you  do  simple,     yet  effecHve,  tesHng?  
  • 20. Name  your  SQL   SELECT /* kmtest */ … FROM tab … SELECT /*+ qb_name (sql42) */ … FROM tab … Comments  stored  with  full  SQL  in  the  SQL_TEXT  column  in  v$sql,  v$sqltext,  dba_hist_sqltext.     QBLOCK_NAME  stored  in  v$sql_plan,  v$sql_plan_staHsHcs_all,  dba_hist_sql_plan.  
  • 21. /*+  gather_plan_staHsHcs  */   (staHsHcs_level  =  ALL)  
  • 22. dbms_xplan.display_cursor   ('ALLSTATS  LAST')  
  • 23. SQL> select /* kmtest */ /*+ gather_plan_statistics */ count(*) from sales ; Plan hash value: 1047182207 ---------------------------------------------------------------------------------------------- | Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers | ---------------------------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1 | | 1 |00:00:00.13 | 4440 | | 1 | SORT AGGREGATE | | 1 | 1 | 1 |00:00:00.13 | 4440 | | 2 | TABLE ACCESS STORAGE FULL| SALES | 1 | 918K| 918K|00:00:00.08 | 4440 | ----------------------------------------------------------------------------------------------
  • 25. dbms_sqltune.report_sql_monitor   (TEXT,  HTML,  XML,  ACTIVE)   Monitored  statements  can  be  found  in  V$SQL_MONITOR  
  • 26. SQL> select /* sql42 */ /*+ monitor */ count(*) from sales ; Global Stats ================================================= | Elapsed | Cpu | Other | Fetch | Buffer | | Time(s) | Time(s) | Waits(s) | Calls | Gets | ================================================= | 0.03 | 0.03 | 0.00 | 1 | 4440 | ================================================= SQL Plan Monitoring Details (Plan Hash Value=1047182207) ====================================================================================================== | Id | Operation | Name | Rows | Cost | Time | Start | Execs | Rows | | | | | (Estim) | | Active(s) | Active | | (Actual) | ====================================================================================================== | 0 | SELECT STATEMENT | | | | 1 | +0 | 1 | 1 | | 1 | SORT AGGREGATE | | 1 | | 1 | +0 | 1 | 1 | | 2 | TABLE ACCESS STORAGE FULL | SALES | 919K | 1230 | 1 | +0 | 1 | 919K | ======================================================================================================
  • 27. @fsx kmtest! ! ! col sql_id new_value r_sqlid! col child_number new_value r_childno! ! ! SELECT /* NOVIEW */ ! ! ! sql_id, child_number ...! FROM gv$sql s! WHERE sql_text like '%&&1%'! AND sql_text not like '%NOVIEW%'! AND sql_text not like 'BEGIN :sql_%'! ORDER BY 1 ;!
  • 28. @dplan! SELECT *! FROM table(dbms_xplan.display_cursor (! ! ! SQL_ID => '&r_sqlid', ! ! ! CURSOR_CHILD_NO => NVL(&r_childno,0), ! ! ! FORMAT => 'ALLSTATS LAST')) ! WHERE '&r_sqlid' IS NOT NULL ;! @rsm! SELECT dbms_sqltune.report_sql_monitor(! ! ! SQL_ID => '&r_sqlid',! ! ! TYPE => 'HTML') ! FROM dual! WHERE '&r_sqlid' IS NOT NULL ;!
  • 29. How  do  you  know  when   refactoring  SQL  is  the   best  opHon?  
  • 30. A  poor  execuHon  plan   is  consistently     developed.  
  • 31. Why  You  Should  Refactor   •  You  know  your  stuff  best  (or  you  should)   •  Always  filter  early   •  Defines  your  expectaHons   •  K.I.S.S.   •  The  opHmizer  might  not  be  able  to  
  • 32. Common  Refactoring     SituaHons  
  • 33. Look  for     "column-­‐less"   joined  tables.  
  • 34. This   SELECT b.* FROM a, b WHERE a.col1 = b.col1 AND b.col2 = <condition> Becomes   SELECT b.* FROM b WHERE b.col2 = <condition> AND EXISTS (SELECT null FROM a WHERE a.col1 = b.col1)
  • 35. Look  for     improper   outer  joins.  
  • 36. This   AND tab1.col1 = tab2.col1 (+) AND tab2.col2 = <condition> Becomes   AND tab1.col1 = tab2.col1 AND tab2.col2 = <condition> Because  the  condiHon  would  be  null  for  the  outer  joined  row,     so  the  predicate  could  never  be  true.  
  • 37. Look  for     repeated  use   of  same  tables   and  predicates.  
  • 38. SELECT rite.event_name, count(*) FROM riffs.rf_order ro, riffs.rf_order_item roi, riffs.rf_item_transaction rit, riffs.rf_item_transaction_event rite WHERE ro.is_test = '0' AND ro.order_id = roi.order_id AND roi.order_item_id = rit.order_item_id AND roi.order_id = rit.order_id AND rit.transaction_id = rite.transaction_id AND (rite.event_name >'AUTHORIZED' OR rite.event_name <'AUTHORIZED') GROUP BY rite.event_name UNION ALL SELECT 'TRANSACTION_INITIATED', count(*) FROM (SELECT count(*) FROM riffs.rf_order ro, riffs.rf_order_item roi, riffs.rf_item_transaction rit, riffs.rf_item_transaction_event rite WHERE ro.is_test = '0' AND ro.order_id = roi.order_id AND roi.order_item_id = rit.order_item_id AND roi.order_id = rit.order_id AND rit.transaction_id = rite.transaction_id AND rite.event_name = 'AUTHORIZED' GROUP BY substr(rit.TRANSACTION_ID,1,INSTR(rit.TRANSACTION_ID,'_')-1))
  • 39. Look  for     simple  predicates   ORed  with  other   predicates  in  ranges.  
  • 40. This   col1 > <condition> OR col2 > <condition> Becomes   col1 > <condition> UNION / UNION ALL AND col2 > <condition> Because  a  row  could  not  be  rejected  when  one  predicate  is  false   without  checking  the  other  predicates.  
  • 41. Look  for   DISTINCT/UNION   to  remove  duplicates.   Consider  using  IN  or  EXISTS  instead.  
  • 42. Think  like  the  opHmizer.   Query  TransformaHon  
  • 43. Simple  View  Merging   is transformed into Merged  automaHcally  as  it  is  deemed  “always  beFer”     for  the  opHmizer  to  work  with  direct  joins.  
  • 44. Complex  View  Merging   is transformed into “Complex”  due  to  GROUP  BY.     CVM  can  also  be  done  when  using  DISTINCT  or  outer  join.  
  • 45. Filter  Push-­‐Down   is transformed into Purpose:  To  push  outer  query  predicates  into  view  to  perform  earlier  filtering.  
  • 46. Predicate  Move-­‐Around   is transformed into Purpose:  To  move  inexpensive  predicates  into  view  query  blocks  to  perform  earlier  filtering.   Can  generate  filter  predicates  based  on  transiHvity  or  funcHonal  dependencies.  
  • 47. Join  FactorizaHon   is transformed into Combines  branches  of  UNION  /  UNION  ALL  that  join  a  common  table  in  order  to   reduce  #  of  accesses  to  that  table.  
  • 48. Understanding  how  the   opHmizer  transforms  queries   helps  you  write  beFer  SQL  and   understand  execuHon  plans.  
  • 49. How  and  When   to  Index  
  • 50. For  many  years,  inadequate  indexing   has  been  the  most    common  cause  of   performance  disappointments.     –    Tapio  Lahdenmäki    
  • 51. Indexing  Problems   •  Indexes  that  do  not  have  sufficient  columns  to   support  all  predicates   •  Not  enough  indexes  present   –  Numerous  single-­‐column  but  few  mulH-­‐column   •  Indexes  with  the  right  columns  but  in  the   wrong  order  
  • 52. How  many  is   "too"  many?  
  • 53. Heavy  DML?   Large,  bulk  loads?   or   Mostly  query?  
  • 54. Indexes  support   query  performance  
  • 55. Inadequate  Index   SELECT !cust_id, cust_first_name! FROM ! !customers! ! WHERE ! !cust_last_name = 'Ruddy'! AND ! ! !cust_city = 'Ede'! ORDER BY cust_first_name ;! Index  present  on  CUST_LAST_NAME,  CUST_FIRST_NAME   #  rows  in  table  =  55,500  
  • 56. Note  the  number  of  rows  that  are  thrown  away  in  step  1  (79).  
  • 57. Index  on  CUST_LAST_NAME,  CUST_CITY   No  throwaway   Index  on  CUST_CITY,  CUST_LAST_NAME,  CUST_FIRST_NAME,  CUST_ID   No  throwaway,  no  sort  
  • 58. Index  Design  Strategies   Columns  from  all  equality  predicates   in  any  order     Add  columns  in  the  order  used  in   ORDER  BY     Add  all  remaining  columns  from   column  list  in  any  order   •  VolaHle  columns  at  end  (reduces  impact  on   updates)  
  • 59. Range  predicates   are  usually  placed  ater   1  and  2  star  columns.   Range  predicates  mean  3-­‐star  indexes  aren't  possible.   The  2nd  star  is  usually  sacrificed  in  preference  of  a  more  selecHve  index.  
  • 60. A  3-­‐star  index  is   oten  called  a   fat   index.    
  • 61. An  index  that  contains  all  the   columns  referenced  in   the  WHERE  clause  is  a     semi-fat   index.     If  no  semi-­‐fat  index  exists,  this  is  a  warning  flag   for  possible  performance  issues.  
  • 62. There  will  always  be  trade-­‐offs.     Test  alternaHves  or  use   "worst  case"  formula  to   esHmate  response  Hmes.      
  • 63. The  key  to  determining  an  ideal  index       The  index  should  provide   adequate  enough  screening   to  minimize  table  accesses.      
  • 64. Recap   •  Look  for  common  anH-­‐paFerns  in  SQL   •  Gather  enough  diagnosHc  data  to  know  where   the  problem  originates   •  Learn  what  the  opHmizer  expects  (and  give  it   what  it  wants!)   •  Think  about  your  indexing  strategy   •  Design  indexes  for  opHmal  coverage  to  limit   table  accesses      
  • 65. Q  &  A