22
© 2005 KPIT Cummins Infosystems Limited We value our relationship Oracle Based Tech Centre of Excellence Best Practices: PL SQL Mahendra Sonawane 10 Aug 2011

Best Practices PL SQL

Embed Size (px)

DESCRIPTION

PL SQL

Citation preview

Page 1: Best Practices PL SQL

© 2005 KPIT Cummins Infosystems Limited

We value our relationship

Oracle Based Tech Centre of

Excellence

Best Practices: PL SQLMahendra Sonawane

10 Aug 2011

Page 2: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Loops, Cursors

2

for i in reverse 1..50 loop s := i;end loop;

Creating a new Cursor based on a Cursor….

Cursor c1 is select ...C2 c1%rowtype;

For a single row sub queryImplicit cursor performs two fetches Explicit cursor performs single fetch.

SELECT INTO statement performs two queriesFetch data from database Determines TOO_MANY_ROWS exception to be raised or not.

Page 3: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

For update where current of cursor

3

For Update : is used to lock cursor fetched rows until commitNormally when other user update rows fetched by cursor, then cursor equerries.declare cursor c1 is select * from emp for update of sal,comm;begin for c in c1 loop update emp set sal = sal + 2000 where current of c1; end loop; commit;end;

Page 4: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Cursor Loop & commit

4

Use rowid column in select clause of cursor.

To mimic WHERE CURRENT OF

ORA-06512: at line # This is called Fetching Across Commits.

ORA-01002: fetch out of sequence

It will raise error

If commit is inside the LOOP

Page 5: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Exception , Mutating , sub query

5

Exceptions Handling

Mutating error? Why ?

What is the workaround ?

Non correlated sub query

The inner query executes first and

for once.

Correlated sub query

The inner query executes

Once for every row of the outer

query.

Nested sub query can have a depth upto 255 levels.

Page 6: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Sub Query

6

SUBQUERY with MULTIPLE COLUMNS joins

could be used in two ways

SQL> …………………………………WHERE (a.mgr, a.eno) IN (

SELECT b.mgr, b.eno FROM ......

)

SQL> ...... WHERE a.mgr||a.eno IN (

SELECT b.mgr||b.eno FROM ......

)

Page 7: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Sub query and Join

7

Best performance depends on

subquery/driving table:SELECT * FROM emp E

WHERE EXISTS ( SELECT 'X' FROM dept D

WHERE D.deptno = E.deptno

AND D.dname = 'SALES');

EXISTS: is better if the number of

matching rows in DEPT are less.

SELECT E.* FROM emp E,dept D

WHERE D.dname = 'SALES'

AND D.deptno = E.deptno;

JOIN: is better if the number of matching

rows in DEPT are largeUse Join instead of Subquery if inner

table has large matching

rows SQL> SELECT *

FROM emp E WHERE E.deptno

IN ( SELECT

D.deptno FROM dept

D WHERE

D.dname = 'SALES');

- Both tables are scanned.

Page 8: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Operators (Some , Any)

8

OPERATORS

Return multiple rows to single row.

(SOME , ANY)

<ANY Less than the sub-query’s

maximum value.

>ANYMore than the sub-query’s

minimum value.

=ANY Equivalent to IN operator.

<ALL Less than the sub-query’s

minimum value.

>ALLMore than the sub-query’s

maximum value.=ALL Equivalent to IN operator.<>ALL

Equivalent to NOT IN

operator.

Page 9: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Set Operators

9

UNION

• It returns unique rows from both the tables and eliminates duplication.

• All unmatched rows from first table.• All unmatched rows from second table.• All matched rows from second table.

UNION ALL

• It returns all rows and duplicates from both the tables.

• Differences between Union and Union all is No Sort occurs on the second case.

INTERSECT• It returns only matched rows from both the tables

and eliminates • duplication. This is equivalent to equi-joins.

MINUS • It returns only unmatched rows from the first table.

Page 10: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Operator precedence

10

Operators

Page 11: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Rules of precedence

11

Arithmetic Operators

Concatenation Operators

Comparison Conditions

IS [ NOT ] NULL, [ NOT ] LIKE, [ NOT ] IN , [ NOT ] BETWEEN

NOT Logical Condition

AND Logical Condition

OR Logical

Page 12: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Uses And , OR

12

When using an "AND" subquery,

place it First:

SQL> SELECT * FROM emp E WHERE E.sal >

50000 AND 25 > (SELECT

COUNT(*) FROM

emp M WHERE M.mgr = E.empno);

- Will take 156 secs. When using an

"OR" subquery, place it last:

SQL> SELECT * FROM emp E WHERE 25 >

(SELECT COUNT(*) FROM

emp M WHERE M.mgr =

E.empno) OR

E.sal > 50000; - Will take 100 secs.

Page 13: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Rownum

13

Select rownum, sal from emp

where rownum = 1; // where rownum = 2;

First one will work but the second one will not return any rows

In implicit cursor record pointer is always in the first record

First it generates the desired results upto the ROWNUM mentioned then returns

Page 14: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Global Temporary Table

14

‘Drop table emp2’

– to drop these types of tables.

On creation,if using subquery, then ON COMMIT clause couldn’t

be used

default is ON COMMIT DELETE

ROWS.

Page 15: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Union , Union All, Count, Bulk Collect

15

Use UNION ALL instead of UNION if there are no

duplicate rows (or if you don't mind

duplicates):

SQL> SELECT * FROM emp

UNION SELECT * FROM

emp_arch;

SQL> SELECT * FROM emp

UNION ALL SELECT * FROM

emp_arch;- UNION: requires sort,

- UNION ALL: no sort and so is faster.

. If the table B has 1 row and A has 16000

rows then SQL> SELECT

COUNT(*) FROM B, A -> time taken

26 secs.SQL> SELECT

COUNT(*) FROM A, B -> time taken 1

secs as B is driving table

Driving table starts at right end of the

from clause

Use Bulk Collect and Bind...

Bulk Collect is used to store record from table

into variable Bulk Bind is used to

insert or update record into table.

These are used for sending and receiving data with the table at

one glance instead one by one record from

PLSQL engine to SQL engine

This makes the operation faster.

This is also called as single context

switching (removing multiple C.S.).

Page 16: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Nocopy

16

This is used for Call By Reference

in case of “ IN OUT “ and “ OUT “ parameter as “ IN “ parameter is by default call by

reference.

Formal parameter : The parameter defined in the parameter list

and used in the program.

Actual parameter : The actual

expression or variable passed to the program

when it is called.

BY VALUE : When an actual

parameter is passed by value, the value of the

actual parameter is copied into the

corresponding formal

parameter. If the program then

terminates without an

exception, the formal parameter

value is copied back to the

actual parameter. If an error occurs,

the changed values are not copied back to

the actual parameter.

BY REFERENCE : When an actual

parameter is passed by

reference, it means that a pointer to the

actual parameter is passed to the corresponding

formal parameter. Both the actual and

formal parameters then

reference, or point to, the

same location in memory that

holds the value of the parameter.

Page 17: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Nocopy

17

Programme

set serveroutput ondeclare

x number := 1;procedure p ( a in out

number) is -- procedure p ( a in out

nocopy number) isc number;

begina := 2;

select partmstr_key into c from tmp_part_masters2 where partmstr_no ='1';

end;

begindbms_output.put_line('bef

ore x = '||x);p(x);

dbms_output.put_line('after x = '||x);exception

when others then

dbms_output.put_line('err x = '||x);

end;

Output

Out put of the above plsql is : When the select statement is

creating error.before x = 1

err x = 1As it was not able to copy the final value

from formal parameter to actual

parameter.Now using NOCOPY, the output will be :

before x = 1err x = 2

As it has already changed the value

of memory location.

Page 18: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Points to remember

18

IN operator can take 1000 lists as maximum and table columns upto 1000.

Procedure can take 64K maximum parameters.

We can write only “RETURN;” statement in procedure and trigger to stop execution

of afterward lines in the sequence.

Function can have only one return value.

If index is created then index will be dropped when table is dropped but view

and sequence will not be dropped

If DDL Statement is correct and execution is not successful due to existence of same object, any

uncommitted transactions get committed

Page 19: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Points to remember

19

BINARY_INTEGER is subtype of INTEGER and assigned values between -2147483647 to 2147483647.

It was the only indexing datatype allowed for index-by tables before ora9i r2 now PLS_INTEGER is also supported.

PLS_INTEGER is subtype of BINARY_INTEGER again -2147483647 to 2147483647, 32 bits,

require less storage than NUMBER values and NUMBER subtypes.

PLS_INTEGER operations use hardware arithmetic rather than

library arithmetic

They are generally faster than NUMBER and INTEGER operations.

For out of range values use INTEGER.

Page 20: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

Points to remember

20

Use NOCOPY in procedure parameter using with long

values or collections.

Make small blocks of begin end, stored procedures, functions and packages.

Use separate rollback segment for large cursors.

Sometimes for large volume records is not good to store in

PL/SQL tables , rather use global temporary tables.To avoid implicit data type

conversion, you can use the built-in functions: TO_DATE,

TO_NUMBER, TO_CHAR, CAST ..

Use ELSIF instead of IF .. END IF; using number of times.

“m NUMBER NOT NULL:=0;” in declare part of PLSQL block is the right way to rather than writing with “IF m IS NULL

THEN raise.. END IF;”.

Page 21: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt

?

21

Any Question

Page 22: Best Practices PL SQL

Version 1.0 Presenter: OB Mgmt 22

Thank You