Presentation on theme: "Presented By Akin S Walter-Johnson Ms Principal PeerLabs, Inc"— Presentation transcript:
1 Presented By Akin S Walter-Johnson Ms Principal PeerLabs, Inc Oracle SQL TuningPresented ByAkin S Walter-Johnson MsPrincipal PeerLabs, Inc
2 SCOPE How data is accessed and reconstituted joins Inform the user on how identify problems with SQLRepair of SQLTuning can occur at 2 levelsServer ( DBA)SQL level ( User)
3 IMPORTANCE OF TUNING Reduce response time for SQL processing To find a more efficient way to process workloadImprove search time by using indexesJoin data efficiently between 2 or more tables
4 HOW TO TUNE Review the access path, Join methods and index usage Test response through SQPLUS directly ( May mask performance )Test response through an Application front end ( Usually takes longer )Test response through a web interface
5 ROLE OF HARDWARE & DESIGN All the hardware in world will not save youMemory, Disk & CPU speed can improve performanceIncreased hardware does not always result into better performancePoor application design accounts for over 70% of performance issuesDo Performance design review early in development
7 OVERVIEW OF SQL PROCESSING The Parser checks both syntax and semantic analysis of SQL statementOptimizer determines the most efficient way of producing the result of the query also known as the EXPLAIN PLAN. How best to get the data.Oracle Optimizer types ( Cost Based and Rule Based )CBO based Optimizer uses cost associated with each execution requires you to analyze objects for statisticsRULE based Optimizer internal rules ( not encouraged by oracle)The SQL Execution Engine operates on the execution plan associated with a SQL statement and then produces the results of the query.
8 SETTING OPTIMIZER SERVER Level by DBA in parameter file (init.ora) CLIENT Level SQLPLUS command < alter session set optimizer_mode=choose>STATEMENT Level using hintsa. select /*+RULE */ * from dual ;b. select /*+ CHOOSE */ * from dual ;Order of PrecedenceSERVER->CLIENT->STATEMENTUsers can set both client and statementTo use CBO you need to analyze the tables (see Analyze objects)
9 OPTIMIZER OPERATIONS THAT AFFECT PERFORMANCE The Optimizer is the brain behind the process of returning data to user it needs to make the following choices.OPTIMIZER APPROACHACCESS PATHJOIN ORDERJOIN METHODChoice of optimizer approachesCBO or RULEChoice of Access Paths ( How data is Scanned )Use an index if not reading all records ( faster)Read or scan all recordsChoice of Join OrdersDetermine which table to join first when you have more than two tables in an SQLChoice of Join MethodsDetermine how to join the tables ( Merge, Sort, Hash )
10 SQLPLUS ENVIRONMENT LAB Log onSet timingAuto Trace to see plan ( How SQL is processed )Set optimizerReview Plan
11 ANALYZE OBJECT STATISTICS Statistics describe physical attributes of an object such asNumber of rows, average space, empty blocksAll objects need to have statistics to use CBOStored in user_tables and user_indexesNot update automatically use analyzeTable StatisticsTable NameNumber of rowsAverage spaceTotal number of blocksEmpty blocksIndex StatisticsIndex_NameIndex_TypeTable_NameDistinct_KeysAvg_Leaf_Blocks_Per_KeyAvg_Data_Blocks_Per_Key
13 TABLE TUNING (i) A Table in oracle store data Resides in a schema within a Table-spaceContains actual data stored in oracle blocksAn oracle block is a multiple of the OS block (Ask your DBA)Row Chaining (Performance killer)A row is too large to fit into on data block so oracle uses more than one chaining themChaining occurs when you try to inset or updateRow migration (Performance killer)There is not enough place in the BLOCK for UPDATESOracle tries to find another Block with enough free space to hold the entire row.( Unnecessary scanning)If a free block is available Oracle moves the entire ROW to the NEW BLOCK.Oracle keeps the original Row piece of a Migrated row row to POINT to the NEW BLOCKQueries that select from chained or migrated rows must perform double read and write (I/O.To find Chained or Migrated table runSQL> ANALYZE TABLE SCHEMA_NAME.TABLE_NAME LIST CHAINED ROWS;SQL> select CHAIN_CNT from user_tables ;
14 TABLE TUNING (ii) Too many empty blocks Occurs after a massive delete then inserting few recordsSelect statement takes a very long time with only one record in tableSolution is to TRUNCATE the table and copy to new table
16 WHY USE AN INDEX What is an Index Oracle Index A pointer or a hand that directs to somethingSimilar to index at the end of a bookOracle IndexBinary tree Structure with entries know as ROWIDLeft nodes contain key and rowidROWID is internal and points to direct location of record on diskROWID is fasted way to reach a record.SQL> Select rowid, id, name from mytable ;
17 OPTIMIZER ACCESS by ROWID ROWID SCANThe fastest way to get a rowBased on the file and the data block where record is locatedUsed also during an index scan
18 OPTIMIZER ACCESS by INDEX UNIQUE SCAN The scan returns only one rowIt requires an index (Primary key)on the TableIndex is automatically created for primary keyUsed by OptimizerWhen an index exist on a column with a where clauseWhen the optimizer is told to use an index (hint) Index hints are not really used.Reading Explain PlanDo a unique scan of the index and obtain ROWIDAccess the table by ROWID
19 OPTIMIZER ACCESS by INDEX RANGE SCAN The scan may return more than one rowUsed by optimizer whenwhere clause has > or < signwhere clause has between 10 and 20where clause has like * ( wild card)
20 OPTIMIZER ACCESS by MULTIPLE UNIQUE SCAN Optimizer will search for ROWID in the statementConcatenate all records into one row setCombining all rows selected by the unique scan into I row setUsed by Optimizer whenwhere clause has an in condition id IN ( 123, 456, 678 )
22 OPTIMIZER ACCESS by FULL TABLE SCAN Each record is read one by oneA sequential search for data no index is usedThe slowest searchOccurs whenThere is no index or index disabledWhen the Optimizer is hinted not to use the index
23 OPTIMIZER ACCESS by FAST FULL INDEX SCAN Alternative to a full table scanUsed by optimizer whenIndex contains all the columns that are needed for the queryIf I want to display only your SSN, you don’t have to access the table if I have SSN as an indexA fast full scan accesses the data in the index itself, without accessing the table
24 OPTIMIZER JOIN METHODA query with more than one table requires to have a Join OrderJoin Order are steps taken to assemble rows of data from more than one tableSelect From A,B,C Where A.col1 = B.Col1 And B.Col2 = C.Col2NESTED LOOPSORT-MERGEHASH JOIN
25 OPTIMIZER JOIN METHOD NESTED LOOP Uses a Looping method to join 2 tableFor every record in A we look thru all rows in B using an index to find a matchTable A is Outer Loop or Driving tableTable B is Inner Loop
27 Nested Loop Good when you expect a small number of rows back Good for Small driving table so not Good if driving table is largeGood when Index on B exist ( will perform poor when no index on B )Good if you want to quickly returns data to the screen ( ONLINE USERS )HINT selectSELECT /*+ ORDERED USE_NL(DEPT) to get first row faster */EMPNO, ENAME, DEPT.DEPTNOFROM EMP, DEPTWHERE EMP.DEPTNO = DEPT.DEPTNO ;
28 OPTIMIZER JOIN METHOD SORT MERGE JOIN In a merge join, there is no concept of a driving tableThe join consists of two steps:Sort join operation: Both the inputs are sorted on the join key.Merge join operation: The sorted lists are merged together.
30 OPTIMIZER JOIN METHOD SORT MERGE JOIN The Merge can’t begin until data sorted from both tablesSince there is a waiting period, this join method will not be good for ONLINE usersGood when you don’t have an index on the join columns, if Index exist a NESTED LOOP is doneGood when NESTED LOOP does not perform whenGood if rows are loaded in a sorted fashionNot Good if you want to quickly return data to the screen ( ONLINE USERS ) need to wait for sorting.Not Good is one of the tables is very,very large because a Full table scan will be done.Good if working with a oracle parallel options because SORTING can be done in parallel
31 OPTIMIZER JOIN METHOD SORT MERGE JOIN Optimizer will use SORT JOIN when index does not exist (May be a warning)Optimizer will use SORT JOIN when OPTIMIZER_MODE is RuleOptimizer will use SORT JOIN when HASH_JOIN_ENABLED is false.HINTSELECT /*+ USE_NL(l h) */
32 OPTIMIZER JOIN METHOD HASH JOIN HASH join compares tow tables in memory to find matching rowsMust set HASH_JOIN_ENABLED to True(DBA )Read first table into memory via Full table scanApply hashing function to data to prepare for join on key fieldsRead second table via Full table scanApply hashing function to compare the second to the first table
34 OPTIMIZER JOIN METHOD HASH JOIN Good only when you have parallel options for oracle because of FTSGood if you have more memory set aside for hashing functionsGood if you indexes don't perform well with NESTED LOOPMay be faster than NESTED LOOP because you are reading in memory as supposed to using indexBetter than SORT MERGE because only on table has to be sorted
36 OPTIMIZER JOIN ORDERAvoid performing unnecessary work to access rows that do not affect the result.Choose the best join order, driving to the best unused filters earliest.
37 OPTIMIZER JOIN ORDER Query 1 SELECT info FROM taba a, tabb b, tabc c WHEREa.key1 = b.key1AND a.key2 = c.key2AND a.acol BETWEEN 100 AND 200AND b.bcol BETWEEN AND 20000AND c.ccol BETWEEN AND 20000
38 OPTIMIZER JOIN ORDER Query 2 SELECT info FROM taba a, tabb b, tabc c WHEREa.acol BETWEEN 100 AND 200AND b.bcol BETWEEN AND 20000AND c.ccol BETWEEN AND 20000AND a.key1 = b.key1AND a.key2 = c.key2;
39 OPTIMIZER JOIN ORDER Query3 SELECT info FROM taba a, tabb b, tabc c WHEREb.bcol BETWEEN AND 20000AND c.ccol BETWEEN AND 20000AND a.acol BETWEEN 100 AND 200AND a.key1 = b.key1AND a.key2 = c.key2;
40 OPTIMIZER JOIN ORDERThe work of the following join can be reduced by first joining to the table with the best still-unused filter.Thus, if "bcol BETWEEN ..." is more restrictive (rejects a higher percentage of the rows seen) than "ccol BETWEEN ...", the last join can be made easier (with fewer rows) if tabb is joined before tabc.
41 OPTIMIZER JOIN ORDERThe driving table is the one containing the filter condition that eliminates the highest percentage of the table.Thus, because the range of 100 to 200 is narrow compared with the range of acol,but the ranges of and are relatively large, taba is the driving table, all else being equal.HINTThe ORDERED hint causes Oracle to join tables in the order in which they appear in the FROM clause.
42 INDEX TUNING Rebuild you index often ( index oil change) Gather statisticsDo not over use IndexesRestrict to cols that return a few recordsUse Bitmapped index when number of values is small e.g ( Sex male, female)Suppression of indexSelect * from mytable where total + 3 = 20
43 REPAIR YOUR SQL STATEMENT LAB Understand the purpose of a statement re-writing may improve performance.Use equi joins on where clauseAvoid column transformationWhere to_number(a.id) = b.idDo not use function in predicateWhere to_string(a.id) = b.idcol1 = NVL (:b1,col1)NVL (col1,-999) = ....TO_DATE(), TO_NUMBER(), and so on
44 REPAIR YOUR SQL STATEMENT LAB WRITE SEPARATE SQL STATEMENTS FOR SPECIFIC TASKSIt is better to use IN rather than EXISTS. , if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS.
45 SQL TUNING CHECK LISTAsk DBA if Cost based optimizer is default in init.oraCheck if you have statistics for tables and indexesCheck if you have a high number of empty blocks on tables(due to large deletes)Check if you have row chaining or row migration on TablesCheck index clusterReview SQL planUse more packages and stored procedures