You are on page 1of 48
What is SQL(Performance) ce and Why We Need?. & Whatis SQL Tuning? % Oracleis a Very Strong Database @ Better Performance - Less Hardware Cost i @ SQL Tuning is the combination of some techniques \ ; & SQL Tuning is not so hard &% Who Will Do the Tuning? SQLTUNING ce ee Bee MASTERCLASS @ No Need to Scare SQL Tuning % You Need to Know Database Architecture in Basic @ There willbe many introductive lectures at first @ SQL Tuning Needs Expertise 1 ~~ | | Some Tools will Not Be Explained y @ AllThe Subjects are Organized Strategically \ y @% Tosumup! SQLTUNING ce ee Bee MASTERCLASS Oracle Database Architecture Rue Rea OE 12° Architecture Diagram Jala SQL TUNING a ee Oracle Database Architecture Rea @ 2 cuENT a ee: Data _ FP bata SQLTUNING ce ee Bee Oracle Database Architecture QRARRARAR Allthe data is storedin Blocks A blockis the smallest unit of database storage Ablockcan have 2KB to 32KB size (8KB default) A block stores row data or index data. Block Header Includes: + Block Type Information + Table Information + Row Directory We can use PCTFREE or PCTUSE parameters to specify the space size in blocks SQL TUNING Poe Pras teers <7 ae a TRG craciemaster@outlootcom Oracle Database Architecture ng _Row Header Column Data SS = _ Row Piece in a Database Block I — sew ord Gabi irate of cotmes Ld [Cetera 0 sed) Hi ron fied Row ns ctann tng Hi coin van SQLTUNING ce ee Bee Oracle Database Architecture @ SESSION AREA + Stores session information of each user. ase es + Stores session variables, login information, session status, etc. @ PRIVATESQL AREA + Persistent area stores the bind variables + Runtime area stores the execution state info. @ CURSORAREA + Stores the information of cursors @ SQLWORKAREA SOUIOTRATEA SQLTUNING ce ee Bee Oracle Database Architecture [AES de @ DATADICTIONARY CACHE + Stores the definitions of the database objects and their permissions @ RESULT CACHE + Stores the result of commonly used queries + Stores the result of functions @ LIBRARY CACHE + stores the execution plans + Stores procedures, packages control structures @ OTHERAREAS SQLTUNING ce ee Bee MASTERCLASS Oracle Database Architecture (Mare @G Largestmemoryarea of SGA. @ Stores the copies of the data blocks read from the disc % Whytoreadinto the buffer cache? + Much fasterthan discs. & Maintained witha complex algorithm | + Stores the most recently used & most touched ones. y % Database write process handles the write ; operations to the disc. Ee : Fb @ Stores the index data, too. SQLTUNING ce ee Bee Oracle Database Architecture Sea Ease Y % @ Oracle Guarantees Not to Lose Data @ ARedoLog Entryis created when insert, update, delete, create, alter, drop occurs @% RedoLog Entries has the changes made to the database @ Theyareused for recovery operations & RedoLog Entries are stored in the Redo (oe Log Buffer vik @% RedoLog Bufferis a circular Buffer Rollback is not done with Redo Log Data SQL TUNING Coe ee Bec eetis sy sae cee Oracle Database Architecture % The original data stored into the memory (undo tablespace) is called as undo data. % Another copy of the datais stored inthe buffer cache for the modifications. % Undo datais not modified because: ‘PDATE + Used for rollback operations DML operations * Used for providing read consistency = Used for providing flashback feature ¥Y Blocks > Extents> Segments > Tablespaces SQLTUNING ce ee Bee a a Oracle Database Architecture PENS aor sXe When we runa DMLcode, the server: Checks the Shared SQL Area for similar statements to use, ‘Checks the Data Dictionary Cache and checks if our query is valid. Checks Buffer Cache & Undo Segments for the related data Locks the related blocks. Makes the change to the blocks in the Buffer Cache. ‘The changes are appliedto the Redo Log Buffer before the Buffer Cache. arene ¥ The server returns the feedback for the change. When the user commits: ¥ The server creates a commit record with SCN. ¥ The LGWr process writes redo log entries in the redo log buffer to the redo log files. ¥ The DBWn writes the dirty blocks to the disc & unlocks the blocks. ¥_ The server retums a feedback about the transaction completion. SQL TUNING master.com BZ craciemaster@outloo Oracle Database Architecture FMA NaN @ The size of each memory area is important for the execution performance of your x queries i @ Oracle can manage the memory ‘) automatically @ Itcanmanage both SGA and PGA memories P % It is recommended to leave automatic ') memory management enabled @ Enabling automatic memory management will prevent out of memory errors SQL TUNING Coe eee Bec ed MASTERCLASS bo sis ae (eae Oracle Database Architecture z @ @ @ Storage = Discs Control Files: Stores the pyhsical structure information of the database. Data Files : Stores Data (Tables, procedures, applicati z data...) Online Redo Log File: tores redo log entries nes Archived Redo Log Files : Online redo log files are constantly moved here 1 ~~] Backup Files : Stores the exact copy of the data files for iieaste recoiey Parameter ie sick ties |“ Arctiveredoog ties Parameter File : Stores the configure data of the s | y database instance ie i Password File: Stores the passwords of the admin users rsssrordse et o5 and Fee tes ] (sysdba, sysoper, sysasm) as k Alert Log & Trace Files : Stores log messages and errors occurredin the database. SQLTUNING ce ee Bee Oracle Database Architecture [er WE Ens Logical @% Blocks: Smallest units of storage (2KB-32KB) @ Extents: Combination of several Database consecutive data blocks. Used for storing specific type of info. @ Segments: Combination of several extents. Tablespace Used for storing some big data (tables, soxmee[ seamen indexes, etc) — @ Tablespaces: Combination of many 7 segments. Used for grouping the related a data in one container — | + Temporary Tablespace: Stores the temporary data ofa Crier + Permanent Tablespace: Storesthe persistent schema objects SQLTUNING Ec eee eee Pras teers <7 Performance Tuning Basics [WHEN TO TUNE? * SQL Tuning is a continuous process = You need to tune your queries: + While creating + Alter the creation * When to decide tuning? + By checking the top consuming queries frequently + After any complaints of bad performance + The reasons of performance loss + Seucturatchanaes + Changes onthe data volume + Application Changes + Aged stanstics + Database Uparaces Operating System & Haravare Changes SQL uN Ne) ce Performance Tuning Basics = Bad SQLs use more resources thannecessary ff yo Ay] IS = Characteristics of a Bad SQL Slime ee Lid + Unnecessary 1/0 operations + Unnecessary CPU time PUT OU ELT a th + Unnecessary walts yt = Time on Wait (CPU) + Time on Execution = DB TIME = The reason of a Bad SQL: = Bad Design, Poor Coding, Inefficient Execution Plan TF SQLTUNING ce Performance Tuning Basics « Select the data types carefully = Assign data types as much as needed * Select exactly the same data type between parent-child keys Enforce data integrity Use normalization well Selectright table type Create Clusters Use indexes often and select index type carefully Create index-organized tables (1OT) ~ z) SQLTUNING ce Performance Tuning Basics Pa SQLTUNING ce Performance Tuning Basics Partitioned SQLTUNING ce Performance Tuning Basics ALTER TABLE employees MODIFY PARTITION BY RANGE (hire date) (PARTITION P_NANEL VALUES LESS THAN (TO_DATE(*@1/01/2018", ‘DD/NK/YYYY")) TABLESPACE USERS, PARTITION PLNAMEZ VALUES LESS THAN (TO_DATE(*01/01/2015", "DD/MM/YYYY")) TABLESPACE USERS, PARTITION PLNAMES VALUES LESS THAN (TO_DATE(*01/01/2020", 'DD/MM/VYWY")) TABLESPACE USERS, PARTITION PLNANES VALUES LESS THAN (MAXVALUE) TABLESPACE USERS, ) ONLINE UPDATE INDEXES (TOXL_SALARY LocaL, TOX2_EMP_ID GLOBAL PARTITION BY RANGE (employee_id) (PARTITION TP VALUES LESS THAN (MAXVALUE)) SQL TUNING Teen Performance Tuning Basics 2 Yes|(Soft parse) SQL TUNING (Hard parse) Poe Performance Tuning Basics Ea SELECT * FROM products WHERE prod_category = ‘Electronics’; ‘Check Schema Information Find Possible Access Pathe Check Statistics: ResuitisTW ofthe whole table, Results 2586oF the whole table \ T Gag Useiindex Read wile Table ) SQL TUNING con pe ee Performance Tuning Basics Cara a Query ‘Transformer tnt 8 cw) «ts _[ [eee Generator le Plan (to Row Source Generation) SQL TUNING Seto BR craciemaster@outlootecom Performance Tuning Basics ERY TRANSFORMER Query transformer transforms the query into a better performing one but semantically equivalent of it If the transform isn’t better, it uses the original one Time restriction and old statistics may lead a wrong plan creation ORExpansion +_Using Onin the where clause will preventindex ueages SELECT * FROM sales MHERE prod_id = 14 or promo.id SELECT * FROM sales WHERE prod_id = 14 UNTON ALL SELECT * FROM sales WHERE promo_id 33 and prod_id © 145 Subquery Unnesting + _Theeptmizer wansferme anested query inte ajo statement SELECT * FROM sales MERE cust_id IN (SELECT custlid FROM customers) SELECT sales." ot sales y customers iW ig HHERE sales.cust_id SQL TUNING Performance Tuning Basics SELECT * FROM sales WHERE proo_ad = 9995 SELECT * FROM salles GHERE prono_id = 9995 + Selec Table has 18.843 017s + promo_id column has 4 distinct values. SELECT * FROM sales WHERE promo id = 335 SELECT num_distinct FROM dba_tab_colunns 7 The Reeaihae aBerowe WHERE table_nane = ‘SALES? 5 [sony aceasta | a as + 7059 distinct values. * Selectivity: 'Y F059 é / * Why Selectivity and Cardinality important? SELECT * FROM sales WHERE cust_id = 100001 + Selectivityatfects the estimatesin NO cost AND prono_id = 999 AND channel_td = 9 + Selectiatyatects the sorecost i U4 + Carinalityisused to determinejoin zortand fier costs . a . + incorroetstecomtyandcardrality=incaectplancostestmatin " Selectivity = 7X FOS Ge SQL TUNING €B wwmoractemastercom FB oraclemaster@outlook.com MASTERCLASS bo sis ae (oes Performance Tuning Basics @ Cost is the optimizer’s best estimate of the number of I/Os to execute a statement. & To estimate the cost, the estimator uses; @ Disk Vo, & CPU usage, @ Memory usage. [See « [mami |s[__ccen Cost = q Single-block read time SQLTUNING ce ee Performance Tuning Basics SELECT e.first_name, e.last_name, e.department_name from FROM employees e, departments d WHERE e.department_id = d.department_id; 2 oraeri]: BEARTMERS[O] ENPLOEESIEZ dein order]: eouovesceley owranensoye0 5 Soin cones 7.57" SQLTUNING ce ee Performance Tuning Basics = Once the plan generator generates the optimum plan, it handles that to the rowsource generator = Rowsource generator generates an iterative execution plan usable for the database = Row sourceis an area that we get the row set (Table, view, result of join or groups) = Row source generator produces a row source tree (A collection of row sources + Row source tree shows the following information : + Execution order / + Access methods 2 + Join methods + Data operations (filter, sort, .) f f SQLTUNING FB vw oraciemastercom ZB oraciemaster@outlooh.com Pras teers <7 Performance Tuning Basics ag ae, i, ar ea ES prod_id = products.prod_id AND prono_id = 33 1 prod_nane, tine ids SQLTUNING ce ee Performance Tuning Basics % SQL Tuning Principles % SQL Tuning Strategies ¥ Identifying the issue Y Parse time reduction ¥ Clarify the details of that issue ¥ Plan comparison strategy ¥ Collecting data ¥ Quick solution strategy ¥ Analyze the data ¥ Finding & implementing a good plan ¥ Choose an appropriate tuning ¥ Query analysis strategy / / strategy x ‘ SQL TUNING Performance Tuning Basics &@ Weuse Query Analysis Strategy when: ¥ Quick tuning strategies did not work, and we have time to work on this problem ¥ Query can be modified ¥ Determine the underlying cause @ Whatto doon this Strategy? ¥ Statistics and Parameters ¥ Query Structure f é ¥ Access Paths ¥ Join Orders & Join Methods ¥ Others s - / é f SQL TUNING oe eee eee MASTERCLASS 4 paths i] fe Cae Performance Tuning Basics * Analyzing the Execution Plan ¥ Tools toget the execution plan ¥ Execution Plan {SOL Trace, KPROF, V8_5QL_PLAN, DEMS MONITOR, AWRSORPTSOL, ete) = Collecting Data V Information of objecte in the query i aes cae ee ¥ ‘Statistics 7 checkithe accom paths ee hack the join reir are the type i compare actual & estimated number of rows (Peremeter: — Find the steps where cost and logical reac are different ¥ The available tools are ‘sgnincancly (SQLT, DBMS. STATS, TKPROF, AWR Report, ete) * Analyzing by considering the query tuning techniques + Find a possible solut + Pre-Analyze of the Query En oa ‘Updating statistics ¥ Check the volume of resulting data + using dynamic statistics ¥ Check the predicates * creating or re-creating an index: + Creating index organized tables (101 Check the problematic constructs, pecs "s a + otters SQL TUNING SS. Execution Plan & Statistics Execution Plan & Statistics Geen = Statistic Types System Statistics Optimizer Statistics. = System Statistics Used by the Optimizer to estimate /O and CPU coste Should be generated regularly ‘Should be gathered during a normal workload * Optimizer Statistics + Can be gathered manually or automatically RUALYZE TABLE COMPUTE STATISTICS GATHER DATABASE STATS Procedure EXEC dbms_stats + GATHER_DICTIONARY_STATS Procedure EXEC doms_stats. gather dictionary stats: + GATHER_SCHEMA STATS Procedure stats(ownnane=> st?) EXEC dbms_stats. gather _schent EXEC db s_stats.gather_systen_stats(‘Start’); + GATHER TABLE STATS Procedure ‘SELECT * FROM sys.aux stats SQL TUNING EXEC dbns_stats. gether_table_stats (ownnat ‘tabname=> ‘SALES?, cascade + GATHER INDEX STATS Procedure Execution Plan & Statistics @ Howcanwe see the Optimizer Statistics? + DBATABLES DBA_TAB_STATISTICS DBA_TAB_COL STATISTICS DBAINDEXES DBA_CLUSTERS DBA_TAB_PARTITIONS / ? DBA_IND_PARTITIONS, DBA_PART_COL STATISTICS a Oi SQLTUNING ce a eee Execution Plan & Statistics * To analyze an execution plan: : { + Explain Plan Kip < + Autotrace + V$SQLPLAN * EXPLAIN PLAN EXPLAIN PLAN FOR Attributes of Indexes E27002 David Motsinger_ £27002 41298 Tim Sampair £03033 * Key Compression 43128 Kim Arlich £10001 + Reverse Key 63535, Timothy Grove __ 16398 * Ascending - Descending Ordered Indexes Table & Index Access Paths 1e@ee1eeeee0e0000101000e000010 @1000111111000100101111111101 @0110000000111010000000000000 wrasse | woman 19 @ 96 0000000000000000000000000 eRe] SS Le Table & Index Access Paths eae > Table Access Paths v Table Access Full v Table Access by ROWID ¥ Sample Table Scan > Index Access Paths Index Unique Scan Index Range Scan Index Full Scan Index Fast Full Scan Index Skip Scan Index Join Sean ry Index Organized Tables. Bitmap Access Paths| * r So Beret) Sn ~~ Bea aca Table & Index Access Paths ee) > Table Access by ROWID occurs when : Tt V ROWID is used in the where clause directly ts v By an Index Scan operation se SQLTUNING [oR ee Be Table & Index Access Paths reuse Table & Index Access Paths IESa se > tthe data we quetied is bounded from one or bethsldes,the optimizer canuse B > theo ‘one ormore le ina. it wil fades a ONIN) See ere ee Table & Index Access Paths DES > All the rows of the tables are indexed by their indexes >» When the optimizer uses the index full scan? > Query has order by clause only with the indexed columns. > Query has group by clause only with the indexed columns. & > Query requires a sort-merge join. a fl SQLTUNING [oR ee Be

You might also like