sql performance vesl technologies

44
11/10/2008 1 Performance Tuning SQL and PL/SQL Presentation By P. S. Mukesh Yadav and Suresh C Mishra VESL TECHNOLOGIES LTD

Upload: suresh-mishra

Post on 29-Nov-2014

372 views

Category:

Self Improvement


2 download

DESCRIPTION

How to standardized querry and code for SQL and PL/SQL

TRANSCRIPT

Page 1: Sql performance vesl technologies

11/10/2008 1

Performance Tuning SQL and PL/SQL

Presentation ByP. S. Mukesh Yadav and Suresh C Mishra

VESL TECHNOLOGIES LTD

Page 2: Sql performance vesl technologies

11/10/2008 2

Topics• Tips in SQL• Tips in PL/SQL

VESL TECHNOLOGIES LTD

Page 3: Sql performance vesl technologies

11/10/2008 3

Tips in SQL

• Limit the use of sub queries; often they can be replaced with a JOIN.

• Use EXISTS and more specific conditions in the where clause instead of the DISTINCT clause to eliminate duplicates.

• Never Mix Datatypes.Use character and number appropriately according to the usage.

VESL TECHNOLOGIES LTD

Page 4: Sql performance vesl technologies

Example of First Tip…

11/10/2008 4

SELECT ename FROM emp dWHERE EXISTS (SELECT e.deptno FROM emp eWHERE 1=1and e.deptno = d.deptnoAND e.comm = 10AND e.sal > 4000);

SELECT ename FROM emp WHERE deptno IN (SELECT deptno FROM emp WHERE comm = 10 AND sal>4000);

SELECT ename FROM emp e,dept dWHERE e.deptno = d.deptnoAND e.comm = 10AND e.sal > 4000

VESL TECHNOLOGIES LTD

Page 5: Sql performance vesl technologies

Example of Second Tip…

Ex :

11/10/2008 5

select distinct ooha.order_type_id,ooha.order_numberfrom oe_order_headers_all ooha,oe_transaction_types_tl otttwhere ooha.order_type_id = ottt.transaction_type_id

SELECT ooha.order_type_id,ooha.order_numberFROM oe_order_headers_all oohaWHERE EXISTS (SELECT 1FROM oe_transaction_types_tl otttWHERE ooha.order_type_id = ottt.transaction_type_id);

VESL TECHNOLOGIES LTD

Page 6: Sql performance vesl technologies

11/10/2008 6

Tips in SQL Contd.. • Avoid the use of NOT IN.Instead, a NOT

EXISTS sub query may run faster.• Use Minus Operator instead of Exists sub

queries(Not in and Not Exists) results in faster execution plan.

• Rewrite (negative(ex : not in)) sub queries as outer joins to improve performance.

• Never use numbers in sorting.

VESL TECHNOLOGIES LTD

Page 7: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 7

SELECT * FROM EMP A WHERE DEPTNO NOT IN (SELECT DEPTNO FROM DEPT WHERE DEPTNO=A.DEPTNO)

SELECT * FROM EMP A WHERE NOT EXISTS (SELECT 1 FROM DEPT WHERE DEPTNO=A.DEPTNO)

select * fromap_invoices_all where invoice_id not in(select invoice_id fromap_invoice_payments_all)

SELECT aia.invoice_id FROM ap_invoices_all aia, ap_invoice_payments_all aipa WHERE aia.invoice_id = aipa.invoice_id(+);

VESL TECHNOLOGIES LTD

Page 8: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 8

select * fromap_invoices_all where invoice_id not in(select invoice_id fromap_invoice_payments_all)

SELECT * FROM ap_invoices_all aia WHERE NOT EXISTS (SELECT * FROM ap_invoice_payments_all WHERE invoice_id = aia.invoice_id)

select * fromap_invoices_allwhere invoice_id in(select invoice_id from ap_invoices_allminusselect invoice_id from ap_invoice_payments_all)

VESL TECHNOLOGIES LTD

Page 9: Sql performance vesl technologies

11/10/2008 9

Tips in SQL Contd..• Avoid running a query in a loop.Make use of

UNION and execute it at the end of the loop. • Avoid the LIKE predicate.Always replace

LIKE with = when appropriate. • Use LIKE rather than the SUBSTR function.• Avoid Where Column Like '%string'.• Consider Indexes for Max() and Min().

VESL TECHNOLOGIES LTD

Page 10: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 10

select * fromdept where dname like 'RESEARCH'

select * fromdept where dname = 'RESEARCH'

select ename from emp where ename like ‘X%’

select ename from emp where substr(ename,1,1) = ‘X’

VESL TECHNOLOGIES LTD

Page 11: Sql performance vesl technologies

11/10/2008 11

Tips in SQL Contd..

• Use Decode and Case for complex aggregations.

• Use WHERE instead of HAVING.• Use UNION ALL instead of UNION.• Prefer using GROUP BY only when any

aggregate functions are present.• Avoid usage of ‘TO_CHAR‘ and use ‘TRUNC‘

instead.

VESL TECHNOLOGIES LTD

Page 12: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 12

SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA

SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA

select * from emp where to_char(emp_joindate,’mmddyyyy’) < to_char(sysdate,’mmddyyyy’)

select * from emp where emp_joindate < trunc(sysdate)

Ex :

VESL TECHNOLOGIES LTD

Page 13: Sql performance vesl technologies

Ex :

11/10/2008 13

SELECT DEPTID,SUM(SALARY)FROM EMPGROUP BY DEPTIDHAVING DEPTID = 100;

SELECT DEPTID,SUM(SALARY)FROM EMP WHERE DEPTID = 100 GROUP BY DEPTID;

SELECT COUNT(*) FROM emp WHERE status = 'Y' AND emp_name LIKE 'SMITH%';

SELECT COUNT(*) FROM emp WHERE status = 'N' AND emp_name LIKE 'SMITH%';

SELECT COUNT(DECODE(status, 'Y', 'X', NULL)) Y_count, COUNT(DECODE(status, 'N', 'X', NULL)) N_count FROM emp WHERE emp_name LIKE 'SMITH%';

VESL TECHNOLOGIES LTD

Page 14: Sql performance vesl technologies

Contd….

11/10/2008 14

SELECT COUNT (*)FROM empWHERE sal < 2000;

SELECT COUNT (*)FROM empWHERE sal BETWEEN 2000 AND 4000;

SELECT COUNT (*)FROM empWHERE sal>4000;

SELECT COUNT (CASE WHEN sal < 2000THEN 1 ELSE null END) count1,COUNT (CASE WHEN sal BETWEEN 2001 AND 4000THEN 1 ELSE null END) count2,COUNT (CASE WHEN sal > 4000THEN 1 ELSE null END) count3FROM emp;

VESL TECHNOLOGIES LTD

Page 15: Sql performance vesl technologies

11/10/2008 15

Tips in SQL Contd..

• Use NVL to check against a number instead of the NULL value.

• Use <= 99 and >= 1 instead of < 100 and > 0 for faster comparisons.

• Avoid using functions on indexed columns.• Use SET TIMING ON to test the execution

time of a slow query.• Use EXPLAIN PLAN to view the execution

steps of a slow query.

VESL TECHNOLOGIES LTD

Page 16: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 16

select cdl.* fromcs_incidents_all_b ciab,jtf_tasks_b jtb,jtf_task_assignments jta,csf_debrief_headers cdh,csf_debrief_lines cdlwhere ciab.incident_id = jtb.source_object_idand jtb.task_id = jta.task_idand jta.task_assignment_id = cdh.task_assignment_idand cdh.debrief_header_id = cdl.debrief_header_idand ciab.incident_number = '1097852'

VESL TECHNOLOGIES LTD

Page 17: Sql performance vesl technologies

Contd….

11/10/2008 17

Operation Object Name Rows Bytes Cost Object Node In/Out PStart PStop

SELECT STATEMENT Optimizer Mode=CHOOSE 4 1134 TABLE ACCESS BY INDEX ROWID CSF_DEBRIEF_LINES 3 414 3 NESTED LOOPS 4 776 1134 NESTED LOOPS 1 56 1131 NESTED LOOPS 1 42 1129 NESTED LOOPS 1 22 1126 TABLE ACCESS BY INDEX ROWID CS_INCIDENTS_ALL_B 1 12 4 INDEX UNIQUE SCAN CS_INCIDENTS_U2 1 2 TABLE ACCESS FULL JTF_TASKS_B 1 10 1122 TABLE ACCESS BY INDEX ROWID JTF_TASK_ASSIGNMENTS 1 20 3 INDEX RANGE SCAN JTF_TASK_ASSIGNMENTS_N2 2 2 TABLE ACCESS BY INDEX ROWID CSF_DEBRIEF_HEADERS 1 14 2 INDEX RANGE SCAN CSF_DEBRIEF_HEADERS_N1 1 1 INDEX RANGE SCAN CSF_DEBRIEF_LINES_N1 4 2

VESL TECHNOLOGIES LTD

Page 18: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 18

select sys.resourceID, sys.client_version0 from dbo.v_R_System as sys where UPPER(netbios_name0) = 'COMPUTER'

select sys.resourceID, sys.client_version0 from dbo.v_R_System as sys where netbios_name0 = 'COMPUTER’

VESL TECHNOLOGIES LTD

Page 19: Sql performance vesl technologies

11/10/2008 19

• Remove unnecessary large full table scans.• Minimize outer joins and use them only if

necessary.• Only use CHAR for data that must be an exact

length such as phone numbers or gender identification fields because it pads variable length data with white-space that will cause string comparisons to fail.

Tips in SQL Contd..

VESL TECHNOLOGIES LTD

Page 20: Sql performance vesl technologies

11/10/2008 20

Tips in SQL Contd..

• Use an indexed column or primary key column when counting rows.

• Avoid unnecessary sorting.• Always better to use base tables instead of

views.• If a view is in a query,try to optimize the view

first before optimizing the query.• Always place all the hard-coded values at the

end of a query.

VESL TECHNOLOGIES LTD

Page 21: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 21

select count(*)From emp

select count(emp _id) from emp;

VESL TECHNOLOGIES LTD

Page 22: Sql performance vesl technologies

11/10/2008 22

• Using the indexes carefully. • Position of Tables in the proper order. • Sequence of Joins in the Where Clause.• Put the queries as simple as possible.• Avoid using of NOT when ever dealing with

Indexed Columns.• Avoid usage of ! Operator use > instead.• Always use a column list in your INSERT

statements.

Tips in SQL Contd..

VESL TECHNOLOGIES LTD

Page 23: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 23

select * from emp where emp_id != 007

select * from emp where emp_id > 0

INSERT INTO EuropeanCountriesVALUES (1, 'Ireland')

INSERT INTO EuropeanCountries(CountryID, CountryName)VALUES (1, 'England')

VESL TECHNOLOGIES LTD

Page 24: Sql performance vesl technologies

11/10/2008 24

Tips in SQL Contd..• Make Use of rownum.• To Check Duplicate Data in a Query.

• Use SQL standards and conventions to reduce parsing.

• Make sure to do INSERT,UPDATE and DELETE operations prior checking the data with a SELECT statement with proper conditions in the where clause.

• Recheck whether any joins are missing.

VESL TECHNOLOGIES LTD

Page 25: Sql performance vesl technologies

Contd….Ex :

11/10/2008 25

SELECT DOCUMENT_NO,COUNT(*)

FROM documents GROUP BY DOCUMENT_NO HAVING COUNT(*) > 1;

VESL TECHNOLOGIES LTD

Page 26: Sql performance vesl technologies

11/10/2008 26

Tips in SQL Contd..• Use Column Names instead of * in a SELECT

Statement.• Use an index on the most queried columns in

SELECT, WHERE, and JOIN statements.• Use BETWEEN instead of IN.• Make sure all joined tables have a matching

join condition.• Make sure columns selected from multiple

tables are dereferenced by an alias.

VESL TECHNOLOGIES LTD

Page 27: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 27

SELECT empno FROM emp WHERE empno IN (508858, 508859, 508860, 508861,508862, 508863, 508864)

SELECT empno FROM emp WHERE empno BETWEEN 508858 and 508864

VESL TECHNOLOGIES LTD

Page 28: Sql performance vesl technologies

11/10/2008 28

Tips in SQL Contd..• Call Functions in SQL Queries.• Minimize Table Lookups in a Query.• Use where instead of Order By.• Never do a calculation on an indexed column.• Give the names from _tl tables instead of

hard-coding the id.Ex : Status• Add Who Columns for any new table created

for easier archiving.

VESL TECHNOLOGIES LTD

Page 29: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 29

select tab_name from tables where tab_name = (select tab_name from tab_columns where version = 604) and db_ver = (select db_ver from tab_columns where version = 604)

select tab_name from tables where (tab_name, db_ver) = (select tab_name,db_ver from tab_columns where version = 604)

update emp set emp_cat = (select max(category) from emp_categories),sal = (select max(salrange) from emp_categories)where emp_dept = 20

update emp set (emp_cat , sal )= (select max(category), max(salrange) from emp_categories) Where emp_dept = 20

VESL TECHNOLOGIES LTD

Page 30: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 30

select * from emp where sal*12>25000

select * from emp where sal>25000/12

VESL TECHNOLOGIES LTD

Page 31: Sql performance vesl technologies

11/10/2008 31

Tips in SQL Contd..• Use sub queries and joins instead of multiple

separate queries.• Use >= instead of >• Use Union in place of OR for Indexed

Columns.• Use the EXISTS clause or = operator instead

of the IN clause whenever you need a single record.

VESL TECHNOLOGIES LTD

Page 32: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 32

select * fromoe_order_headers_allwhere order_number>3

select * fromoe_order_headers_allwhere order_number>=4

VESL TECHNOLOGIES LTD

Page 33: Sql performance vesl technologies

11/10/2008 33

Tips in SQL Contd..• Avoid IS NULL & IS NOT NULL on Indexed

Columns.Use >=0 if necessary.• Use a system generated ID as the primary

key to avoid duplicates.• Use Optimizer Hints.• Generate a tkprof and observe the trace file.• Focus on critical transactions(Production

Data)..

VESL TECHNOLOGIES LTD

Page 34: Sql performance vesl technologies

Contd….

Ex :

11/10/2008 34

/*+index(t1) index(t2)……..index(tn)*//*+FULL(t1) FULL(t2)……FULL(tn)*//*+OPTIMIZER_GOAL=CHOOSE*//*+OPTIMIZER_GOAL=FIRST_ROWS*//*+ORDERED*//*+RULE*//*+OPTIMIZER_GOAL=ALL_ROWS*//*+OPTIMIZER_GOAL=ORDERED*//*+OPTIMIZER_GOAL=RULE*//*+USE_NL(t1,t2,t3,t4,t5,t6) ORDERED */

VESL TECHNOLOGIES LTD

Page 35: Sql performance vesl technologies

11/10/2008 35

Tips in PL/SQL

• Break the piece of code into small blocks to achieve modularity.

• Grouping related logic as a single block.• Use Packages for each major functionality. • Avoid hard-coding.

VESL TECHNOLOGIES LTD

Page 36: Sql performance vesl technologies

11/10/2008 36

Tips in PL/SQL Contd..

• Follow PL/SQL Coding standards for procedures, variables, table types,rec types, functions and packages.

• Encapsulate your SQL.• Avoid repeating the SQL in different places.• Exception Handling.• Usage of Bind Variables and Global Variables.• Make Function Calls efficiently.

VESL TECHNOLOGIES LTD

Page 37: Sql performance vesl technologies

11/10/2008 37

Tips in PL/SQL Contd..• Use BULK COLLECT when there is huge

amount of data to be fetched from a select query in a cursor.

• Use FOR ALL. • Use Bulk Bind.• Reorder Conditional Tests to put the Least

Expensive First.• Logic in a simplest way.• Usage of End Labels.• Avoid usage of mutating tables.

VESL TECHNOLOGIES LTD

Page 38: Sql performance vesl technologies

Contd….• Ex :

11/10/2008 38

CREATE OR REPLACE FUNCTION get_a_mess_o_emps (deptno_in IN dept.depno%TYPE)RETURN emplist_tIS emplist emplist_t := emplist_t(); TYPE numTab IS TABLE OF NUMBER; TYPE charTab IS TABLE OF VARCHAR2(12); TYPE dateTab IS TABLE OF DATE; enos numTab; names charTab; hdates dateTab;BEGIN SELECT empno, ename, hiredate BULK COLLECT INTO enos, names, hdates FROM emp WHERE deptno = deptno_in; emplist.EXTEND(enos.COUNT); FOR i IN enos.FIRST..enos.LAST LOOP emplist(i) := emp_t(enos(i), names(i), hiredates(i)); END LOOP; RETURN emplist;END;

VESL TECHNOLOGIES LTD

Page 39: Sql performance vesl technologies

Contd….

• Ex :

11/10/2008 39

PROCEDURE reality_meets_dotcoms (deptlist dlist_t)ISBEGINFORALL aDept IN deptlist.FIRST..deptlist.LAST DELETE emp WHERE deptno = deptlist(aDept);END;

VESL TECHNOLOGIES LTD

Page 40: Sql performance vesl technologies

11/10/2008 40

Tips in PL/SQL Contd..• Use Anchored declaration during declaration of

variables.• Reduce N/w traffic.• Make use of ‘user_’ tables or views in the custom

packages.• Use Standard Public Apis.• Group related sub-programs in a Package.• Make use of Optimizer Hints.

VESL TECHNOLOGIES LTD

Page 41: Sql performance vesl technologies

11/10/2008 41

Tips in PL/SQL Contd..

• Make use of the apis being called in the standard forms of Oracle Applications.

• Minimize Datatype Conversions. • Use of CASE statements, is a much better

alternative to nested if-elsif statements.• Declare Local Variables – Oracle Datatype.• Make Loops as Efficient as Possible.

VESL TECHNOLOGIES LTD

Page 42: Sql performance vesl technologies

11/10/2008 42

Tips in PL/SQL Contd..

• Use of pls_integer to declare integers and binary_float or binary_double for floating point.

• Replace and simplify IF statements with Boolean expressions.

• Never exit from a FOR or WHILE loops.• Never declare the FOR loop index (either an

integer or a record). • Minimize the function Calls.

VESL TECHNOLOGIES LTD

Page 43: Sql performance vesl technologies

11/10/2008 43

Contd……

Unit Testing. Debugging. Analysis on the Exceptions. Test Cases.

VESL TECHNOLOGIES LTD

Page 44: Sql performance vesl technologies

11/10/2008 44

Contd…

Thank You

VESL TECHNOLOGIES LTD