Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Oracle

Tips and
Tricks
BY AJIT BAKSHI
To understand anything we must have an open mind

IDBI Intech Pvt. LTD


Table of Contents

Table of Contents
Oracle Database Details________________________________________________________1
Instance Details_____________________________________________________________1

Tablespace Details__________________________________________________________1

User Details________________________________________________________________2

Server Details______________________________________________________________2

SQL*Plus Tips and Tricks_______________________________________________________3


Understanding of SQL*Plus___________________________________________________3

SQL and PL/SQL TIPS and Tricks________________________________________________5


How to transpose rows to columns______________________________________________5

How to transpose columns to rows______________________________________________5

How to use Bulk collect_______________________________________________________6

Auto addition of Partition to table and compression on Tablespace level and Table level____6

How to Enable and Use LDAP in oracle__________________________________________7

Storing CLOB values into BLOB________________________________________________7

Generate XML from SQL Query________________________________________________7

Creating and Using Custom Records and Collections_______________________________7

Creating and Using Nested Structure Tables______________________________________8

Implementation of Message Queue in Oracle______________________________________8

Ready code to Print Refcursors________________________________________________9

Indian Rupee Converter Function_______________________________________________9

Brain Teaser with Dates______________________________________________________9

Timestemp based recovery___________________________________________________10

Exit when error occurs in sql script_____________________________________________10

Convert Delimited Text to Row in SQL__________________________________________10

Get Bind variable details_____________________________________________________10

Try to Avoid the Like’s_______________________________________________________11

Use of dbms_assert package_________________________________________________11

With clause different flavor___________________________________________________12


Table of Contents

Pragma UDF______________________________________________________________12

SQL Macros - Creating parameterized views_____________________________________12

NOCOPY Hint to Improve Performance of OUT and IN OUT Parameters in PL/SQL Code_13

Measure PL/SQL Block timings________________________________________________14

Performance Tuning__________________________________________________________15
What to look for____________________________________________________________15

Techniques/Tools to use_____________________________________________________15

Example_________________________________________________________________16

Other useful tools and tips _____________________________________________________18


Change timestamp of a fine in UNIX____________________________________________18

Take database backup to remote database for selected tables using EXPDP____________18

orapki Utility/Oracle Wallet___________________________________________________19

RMAN Backups____________________________________________________________21

Coding Standards____________________________________________________________22
For PL/SQL_______________________________________________________________22

Notes to User of this Document_________________________________________________24


Company Information_________________________________________________________24
Other useful tools and tipsOther
Pg. 1 useful tools and tips

Know your
environment Oracle Database Details

Instance Details
SGA and PGA Parameters are crucial for Query Performance, Higher is better.

 Points to Ponder
1. Ratio of SGA to PGA is 80-20 for OLTP systems and 50-50- for OLAP/Memory
intensive queries
2. Always keep details of SGA and PGA parameters of database you are working with

 Important views
V$PGASTAT
V$PROCESS
V$SQL_WORKAREA_HISTOGRAM
show sga – Command on sqlprompt

 Oracle Hidden Parameters


_pga_max_size - - this hidden parameter defaults to 200 MB
_smm_px_max_size - This parameter is used for Oracle parallel query, and defaults to
30% of the pga_aggregate_target setting, divided by degree of parallelism

*Caution these parameters need to be tempered with consultation to DBA and need to be
approved by oracle ACS support.

Tablespace Details
Tablespaces stores the data of tables, information about databse objects, backups taken,
history of changes done in objects and many more things.

Points to Ponder
1. Take a note of available tablespaces and associated data files
2. Ensure >30 space is free on disks for data file expansion up to 32 GB and addition of
data files to tablespace after that.
3. Choose compression with OLTP for bigger and historic tables
Other useful tools and tipsOther
Pg. 2 useful tools and tips

4. Have separate tablespaces for Tables and separate tablespace for Indexes
Know your
environment
User Details
The database user enables us to connect to oracle database and store the relevant
data.

Points to Ponder

1. Carefully take a note of user’s roles, grants and quota.


2. Basic user need below array of grants to be able to connect and do the operations
CREATE SESSION, CREATE DATABASE LINK, CREATE SYNONYM, CREATE
PROCEDURE, CONNECT, RESOURCE
3. Username once created can’t be altered.

Server Details
Server where database is installed, we need to take a note of its details like

1. Server IP
2. CPU(CPU Class ,clock speed, No Of CPU, Cores, Entitled CPU, POOL CPU), Memory
(Allocated/Entitled Physical Total memory, Virtual Memory)
3. Server is Physical/VM/LPAR
4. How many databases are running on the same server/On the other LPAR of the same
box
5. Get NMON reports periodically
6. Technology Level (TL level) of server
7. Hardware type
8. OS version
9. Machine Type
10. Physical Location of Server
11. Segment of Server(DR,DC,PROD)
Other useful tools and tipsOther
Pg. 3 useful tools and tips

SQL*Plus
Goodies
SQL*Plus Tips and Tricks
The sql*plus utility has some unique features to help and execute the SQL commands or SQL
files.

Understanding of SQL*Plus
1. sqlplus –help

The above commands shows all the parameter of sql*plus

2. @<filename.sql> is equal to get <filename.sql>


3. HOST or HO command enables us to execute OS commands. (i.e. when on windows
we can create a file, use commands like mkdir, copy, move etc or can execute a .exe
or batch file from within an filename.sql
Example on Windows use command prompt:

C:\Users\int7075>type Myfile.sql

set head off echo off verify off feedback off trimspool on pagesi 0 linesi 1000
spool Open_notepad.bat
select ‘notepad My_text.txt’
from dual;
spool off;
spool My_text.txt
select ‘Hi this is a beautiful day’
from dual;
spool off;
ho Open_notepad.bat
select ‘Program execution completed’ from dual;
Other useful tools and tipsOther
Pg. 4 useful tools and tips
Other useful tools and tipsOther
Pg. 5 useful tools and tips

SQL*Plus
Goodies 4. Least used but very useful command is
COPY {FROM database | TO database | FROM database TO database}
{APPEND|CREATE|INSERT|REPLACE} destination_table [(column, column, colu
mn, ...)] USING query
Example

COPY FROM RETMIS@RETMIS TO RETMIS@DAILYMIS REPLACE SOL USING


SELECT * FROM SOL;

Please note, Here “@RETMIS” and “@DAILYMIS” are tnsnames.ora entries on the
server/machine where we are executing this command also, this can be replaced with
EZ Connect method(Host, port,ip, sid)
5. Store query output in a variable and use it to replace object name on runtime
<Example>
col MYVAR noprint new_value MY_TAB_VAR
select 'MY_TABLE'||to_char(report_date,'DD-MON-YYYY') MYVAR
from dual;

select *
from &MY_TAB_VAR;

Here MYVAR is the column name, MY_TAB_VAR is the variable where the value
MY_TABLE12JAN2025 will be stored. \
Later we are using this table variable to run the desired queries/scripts.
Scope of this variable till the SQL session lasts.
Other useful tools and tipsOther
Pg. 6 useful tools and tips
SQL Tips and
Tricks
SQL and PL/SQL TIPS and Tricks
How to transpose rows to columns
select
regexp_substr(acct_labels,'[^|]+', 1,1) pos1,
regexp_substr(acct_labels,'[^|]+', 1,2) pos2,
regexp_substr(acct_labels,'[^|]+', 1,3) pos3,
regexp_substr(acct_labels,'[^|]+', 1,4) pos4,
regexp_substr(acct_labels,'[^|]+', 1,5) pos5,
regexp_substr(acct_labels,'[^|]+', 1,6) pos6,
regexp_substr(acct_labels,'[^|]+', 1,7) pos7,
regexp_substr(acct_labels,'[^|]+', 1,8) pos8
from(
select RTRIM(XMLAGG (XMLELEMENT (E, acct_label || '|')).EXTRACT ('//text()'),',') acct_labels
from (select rownum||'~'||acct_label acct_label
from alr
where acid = 'DC1424978' ))

Here XMLAGG this function will add-up rows into single column , regexp_substr this function
will split the contents of single column to multiple separate columns

How to transpose columns to rows


create table test (
sr varchar2(1),col1 number,col2 number,col3 number
);
insert into test values ('a',1,2,3);
insert into test values ('b',4,5,6);
insert into test values ('c',7,8,9);

select * from test


unpivot (
val for col in ( col1, col2, col3 )
);

Or use
select *
from TABLE( cols_as_rows('select *
from emp
where rownum = 1') );
Other useful tools and tipsOther
Pg. 7 useful tools and tips
SQL Tips and
Tricks
How to use Bulk collect
In PL/SQL Bulk collect is a powerful method to process large amount of data. Example
attached below.

Auto addition of Partition to table and compression on


Tablespace level and Table level
Partitions are grate way to manage very large tables. If your partitioning and indexing
strategies are good query results will be fast, let be your database in GB or TB or PB. Below is
the example of Range partition where daily a new partition will be created for storage of data.
Remember, older date partitions can be merged into Monthly single partition and Monthly to
Yearly Partition through separate job/tasks.
Other useful tools and tipsOther
Pg. 8 useful tools and tips
SQL Tips and
Tricks
How to Enable and Use LDAP in oracle
Single sign on helps on various levels here is how to do in Oracle. Below Program creates
Network ACL rule in database to connect to LDAP server, later we call a small program to
connect and validate the User id and Password of LDAP User.

Storing CLOB values into BLOB


The CLOB can contain large amount of textual data in Oracle 19c Maximum size: (4 GB - 1) *
DB_BLOCK_SIZE initialization parameter (8 TB to 128 TB Approx.* depending on the DB Block size).
BLOB columns are used to store large and unstructured data such as text, image, video, and spatial
data. BLOB is designed for efficient storage of large objects.

Generate XML from SQL Query


We can use a simple function to generate XML Output from a query

select dbms_xmlgen.getxml('select acid, acct_label acct_label from alr where acid =


'||''''||'DC1424978'||'''') FROM DUAL;

Creating and Using Custom Records and Collections


In PL/SQL We can create custom record types and Process data and store in these custom
records.

Below is the code to do so


Other useful tools and tipsOther
Pg. 9 useful tools and tips
SQL Tips and
Tricks
Creating and Using Nested Structure Tables
Nested Tables resembles real life objects. The OOP in oracle can be demonstrated by the
Nested tables

The attached below example takes customer details and its account details in a parent child
relationship as nesting. In this example we created Database objects, we can use this
construct in PL/SQL as well.

Implementation of Message Queue in Oracle


Like Java Queues in Oracle there is Advance Queue Feature. The Queues helps to send
messages across database.

These features are supported in Oracle AQ


 Transaction support, Publish/Subscribe support ,Quality of Service (QoS)
 Queue Models
 Security
 Message Propagation, Message Transformation, Rules-based Message Routing
 Priority of Messages

Below is the simple implementation of Message Queue in Oracle. We require 2 separate SQL
sessions connected with same database to send the message and receive the message on
other session.

Below are the grants required on the user

GRANT aq_administrator_role TO <MYUSER>; GRANT connect TO <MYUSER>; GRANT


create type TO <MYUSER>;
Other useful tools and tipsOther
Pg. 10 useful tools and tips
SQL Tips and
Tricks
Ready code to Print Refcursors
Ever created a function or procedure with returning refcursor ? and wondering how to test it ?
Here is the ready code to do so.

variable rc0_P_CUR refcursor;


DECLARE
INP_EID NUMBER;
P_CUR SYS_REFCURSOR;

BEGIN
INP_EID := 107513;
-- P_CUR := NULL; Modify the code to initialize this parameter
AJIT.HRMS_EMP_BELOW ( INP_EID, P_CUR );
:rc0_P_CUR := P_CUR;
COMMIT;
END;

print rc0_P_CUR; -- This will print output of cursor on Script output/Grid in Toad/ SQL Prompt

Indian Rupee Converter Function


Every wanted to create number to Indian rupee and Paisa for your Application? Here is the
code for it

Brain Teaser with Dates


Try the brain teaser below and understand the Months_between function behavior
Other useful tools and tipsOther
Pg. 11 useful tools and tips
SQL Tips and
Timestemp based recovery
Tricks
Select *
from dsb_deposit_temp
as of
timestamp TO_TIMESTAMP ('2018-03-03 14:00:00','YYYY-MM-DD HH24:MI:SS');
This timestamp based selection is based on re-do log period, beyond its time details can’t be
fetched.

Exit when error occurs in sql script


Example as below

Convert Delimited Text to Row in SQL


/*******************/
delimited text to rows
/*****************/

with t as (select 'abcd,123,defoifcd,87765' as str from dual)


select level as n, regexp_substr(str,'[^,]+',1,level) as val
from t
connect by regexp_substr(str,'[^,]+',1,level) is not null

Get Bind variable details


Other useful tools and tipsOther
Pg. 12 useful tools and tips
SQL Tips and
Tricks Try to Avoid the Like’s
Whenever we use Like in SQL query, the Query may or may not follow the index based on the
same column. Pattern searches are slow when we do ‘%EMP%’ or %‘ACLABEL%’. The
overhead can be avoided by using SUBSTR function.

For example:-

See the cost difference

select count(1) from alr


where acct_label in (select acct_label_code from alc where acct_label_code like '%BC%');

select count(1)
from alr
where acct_label in (select acct_label_code from alc where substr(acct_label_code,1,2) =
'BC');

Use of dbms_assert package


Use DBMS_ASSERT package for following

 Applying quotes/ Remove quotes (Single , Double)


 Validate Schema/Object/SQL Name
Other useful tools and tipsOther
Pg. 13 useful tools and tips

With clause different flavor


While we use with clause to define repetitive tables under with clause to eliminate the oracle
parsing the same table multiple times, we can define functions under with clause to avoid the
SQL to PL/SQL context switching completely. This improves the performance by a lot.

Example
WITH
function myfunction(x int) return int as
begin
...
return ...
end;
select myfunction(col) from my_table

Pragma UDF
The UDF pragma tells the compiler that the PL/SQL unit is a user defined function that is used
primarily in SQL statements, which might improve its performance. (Primarily it tells oracle
SQL engine that this program unit is to be called mostly by SQL and optimize the same
accordingly by reducing the context switch using bulk/batch passes internally from SQL to
PL/SQL and reduces fetch size).

create or replace function MYFUNCT(x number) return number is


pragma udf;
begin
return x*2;
end;

SQL Macros - Creating parameterized views


It's a new, simpler way to encapsulate complex processing logic directly within SQL.

SQL Macros allow developers to encapsulate complex processing within a new structure
called a "macro" which can then be used within SQL statement.

SQL Macros have an important advantage over ordinary PL/SQL functions in that
they make the reusable SQL code completely transparent to the Optimizer – and that
brings big benefits! It makes it possible for the optimizer to transform the original code for
efficient execution because the underlying query inside the macro function can be merged
into outer query. That means there is no context switching between PL/SQL and SQL and
Other useful tools and tipsOther
Pg. 14 useful tools and tips

the query inside the macro function is now executed under same snapshot as outer query.
So we get both simplicity and faster execution.

Essentially there two types of SQL Macros: SCALAR and TABLE. What's the difference:

 SCALAR expressions can be used in SELECT list, WHERE/HAVING, GROUP


BY/ORDER BY clauses (Not Available at present in 19C)
 TABLE expressions used in a FROM-clause (available from Oracle 19C onwards)

Example
CREATE OR REPLACE FUNCTION total_sales(zip_code varchar2) return varchar2 SQL_MACRO is
BEGIN
RETURN q'{
SELECT cust.cust_postal_code as zip_code,
SUM(amount_sold) as revenue
FROM sh.customers cust, sh.sales s
WHERE cust.cust_postal_code = total_sales.zip_code
AND s.cust_id = cust.cust_id
GROUP BY cust.cust_postal_code
ORDER BY cust.cust_postal_code
}';
END;
/

SELECT *
FROM total_sales(zip_code => '60332');

NOCOPY Hint to Improve Performance of OUT and IN OUT


Parameters in PL/SQL Code
Oracle has two methods of passing OUT and IN OUT parameters in PL/SQL code:

Pass By Value

The default action is to create a temporary buffer (formal parameter), copy the data from the
parameter variable (actual parameter) to that buffer and work on the temporary buffer during
the lifetime of the procedure. On successful completion of the procedure, the contents of the
temporary buffer are copied back into the parameter variable. In the event of an exception
occurring, the copy back operation does not happen.
Other useful tools and tipsOther
Pg. 15 useful tools and tips

Pass By Reference

Using the NOCOPY hint tells the compiler to use pass by reference, so no temporary buffer is
needed and no copy forward and copy back operations happen. Instead, any modification to
the parameter values are written directly to the parameter variable (actual parameter).

Under normal circumstances you probably wouldn't notice the difference between the two
methods, but once you start to pass large or complex data types (LOBs, XMLTYPEs,
collections etc.) the difference between the two methods can be come quite considerable. The
presence of the temporary buffer means pass by value requires twice the memory for every
OUT and IN OUT parameter, which can be a problem when using large parameters. In
addition, the time it takes to copy the data to the temporary buffer and back to the parameter
variable can be quite considerable.

The following tests compare the elapsed time and memory consumption of a single call to test
procedures passing a large collection as OUT and IN OUT parameters.

Measure PL/SQL Block timings


However there are various ways to measure the PL/SQL timings, the DBMS_PROFILER is the
best way so far to understand and analyze the individual block timings, how many times a
block has run and other details

To run the DBMS_PROFILER we need to have few base tables in place


Other useful tools and tipsOther
Pg. 16 useful tools and tips
Performance
Tuning
Performance Tuning
What to look for
Before thinking of tuning, we must answer below questions with descending priority

1) Have we calculated baseline for existing process that need to tune?


2) What is our expectation and what is the basis of our expectation?
3) Are there any examples where the same process is running faster?
4) How many years ago the program was written?
5) Are we ready to change the program as per latest Software features?
6) What are our system, Hardware, Network boundary/Limitations?
7) Do we have the perfmon/nmon/OEM/ADDM/AWR/ASH periodic reports?
8) Has all bottlenecks listed in these reports identified and resolved/mitigated?
9) Is the SQL tuning advisor has been run for listed queries in AWR, ADDM reports?

Techniques/Tools to use
We can use below tools

 Indexes
 Statics gathering on tables
 Analyzing tables
 Identification of Bad Queries through AWR/ASH/ADDM reports
 Check SQL Explain plan
 Use of tools like , Log miner , tkprof
 Try to eliminate the FULL SCANS wherever possible
 Index need to be rebuild after data inserted in bulk
 Try to eliminate multiple hops between different databases by using session
tables/global temporary tables/privet temporary tables
 Pl/SQL codes where we are processing each record one by one, in such cases
insert/updates, bulk update/insert must be used.
 Break larger process into smaller chunk of process
 Partition bigger tables
 Keep the database clean with no un-wanted backup tables
Other useful tools and tipsOther
Pg. 17 useful tools and tips

 Use of hints in query

Example
-- 15 Minutes
CREATE TABLE tmp_cmg_laa2 AS
SELECT cust_id,cust_const FROM tbaadm.cmg a WHERE cust_id in
( SELECT cust_id FROM tmp_npa_acid b group by cust_id );
Explain plan

When changed to
CREATE TABLE tmp_cmg_laa2 AS
SELECT cust_id,cust_const FROM tbaadm.cmg a WHERE cust_id in
( SELECT cust_id FROM tmp_npa_acid b group by cust_id )
Where 1=2;

-- 10 Miutes
insert /*+ APPEND NOLOGGING */ into tmp_cmg_laa2
SELECT cust_id,cust_const FROM tbaadm.cmg a WHERE cust_id in
( SELECT cust_id FROM tmp_npa_acid b group by cust_id );

Now using global temperory table


Other useful tools and tipsOther
Pg. 18 useful tools and tips

-- .01 ms
CREATE TABLE tmp_cmg_laa2 AS
SELECT cust_id,cust_const FROM tbaadm.cmg a WHERE cust_id in
( SELECT cif_id FROM idbi.idbib_reports_table);

-- 11 seconds 1378329
insert into idbi.idbib_reports_table(cif_id)
SELECT cust_id FROM tmp_npa_acid b group by cust_id ;

-- 6 secs Insert 1378329


insert /*+ APPEND PARALLEL(32) NOLOGGING */ into tmp_cmg_laa2
SELECT cust_id,cust_const FROM tbaadm.cmg a WHERE cust_id in
( SELECT cif_id FROM idbi.idbib_reports_table);

COMMIT;

Process completed in less than 1 min.

Warning:- NOLOGGING is used only for non-production databases, where we don’t have DR
setups. Do not use this hint otherwise.
Other useful tools and tipsOther
Pg. 19 useful tools and tips
Other useful tips

Other useful tools and tips


Change timestamp of a fine in UNIX
touch -t 201410111744 filename.txt

Take database backup to remote database for selected tables


using EXPDP
We are on a backup server and want to take remote database backup through database link

In this case we need to execute below shell script run_bkp.com

cat run_bkp.com
while IFS="" read -r p || [ -n "$p" ]
do
echo "$p"
echo "================== Starting Backup =========================="
bkp.com $p
echo "================== Backup Completed =========================="
done < tbl_lst.txt

cat bkp.com
conn='//10.144.16.196:1521/rbs'
Other useful tools and tipsOther
Pg. 20 useful tools and tips

#conn="\(DESCRIPTION =\(ADDRESS_LIST \= \(ADDRESS \= \(PROTOCOL = TCP\) \(HOST


\=10.144.16.196\)\(PORT \= 1521\)\)\
) \(CONNECT_DATA = \(SERVICE_NAME = rbs\)\)\)"
echo $conn
impdp EISRBS/eisrbs@"$conn" tables=TBAADM.$1 PARFILE=exclude.par

cat exclude.par
REMAP_TABLESPACE=TBA_TEMP:EIS
EXCLUDE=STATISTICS
EXCLUDE=AUDIT_OBJ
EXCLUDE=GRANT
EXCLUDE=INDEX
NETWORK_LINK=MIS46
DIRECTORY=TMP_EXP_IMP
LOGFILE=IMP_EISRBS.log
TABLE_EXISTS_ACTION=REPLACE
REMAP_SCHEMA=TBAADM:EISRBS
PARALLEL=6

Explanation
Here the run file will take table name from tbl_lst.txt one by one and take the database to
database export from Monthly MIS server to REMOTE EIS server.
This technique will require the database link on Remote database server. We will connect to
remote database server and pull the data from Monthly MIS server.
This method of Export/Import data pump doesn’t require to create dump files on disks.
It will directly create tables on Remote database with the parallel power of EXP DP.

orapki Utility/Oracle Wallet


The orapki (creates Self-Signed SSL Certificates) utility makes handling certificates and Oracle
wallets very simple. It also allows password-less login to database from the machine where the
wallet is created which further allows it to be used with Data Pumps and other utilities which
requires connection to database.

1) Create a location for your wallet.

2) Add the location of the orapki utility to your path.


Other useful tools and tipsOther
Pg. 21 useful tools and tips

$ mkdir /home/oracle/wallet
$ cd /home/oracle/wallet
$ export PATH=$PATH:$ORACLE_HOME/bin

3) Create a wallet to hold your certificate.

4) Create a self-signed certificate and add it to your wallet.

$ orapki wallet create -wallet ./ -pwd WalletPasswd123 -auto_login


$ orapki wallet add -wallet ./ -pwd WalletPasswd123 \
-dn "CN=`hostname`, OU=Example Department, O=Example Company, L=Birmingham,
ST=West Midlands, C=GB" \
-keysize 1024 -self_signed -validity 365

5) You can check the contents of the wallet with the following command.

$ orapki wallet display -wallet ./ -pwd WalletPasswd123

Requested Certificates:
User Certificates:
Subject: CN=rhce1.localdomain,OU=Example Department,O=Example
Company,L=Birmingham,ST=West Midlands,C=GB
Trusted Certificates:
Subject: OU=Class 3 Public Primary Certification Authority,O=VeriSign\, Inc.,C=US
Subject: CN=GTE CyberTrust Global Root,OU=GTE CyberTrust Solutions\, Inc.,O=GTE
Corporation,C=US
Subject: OU=Class 2 Public Primary Certification Authority,O=VeriSign\, Inc.,C=US
Subject: OU=Class 1 Public Primary Certification Authority,O=VeriSign\, Inc.,C=US
Subject: CN=rhce1.localdomain,OU=Example Department,O=Example
Company,L=Birmingham,ST=West Midlands,C=GB

Note these certificates can be consumed in the Web applications as well to connect/allow API
based transactions.
Other useful tools and tipsOther
Pg. 22 useful tools and tips

RMAN Backups
RMAN is a subject rather than a topic.

Recovery manager is a platform independent utility for coordinating your backup and
restoration procedures across multiple servers. The reporting features alone mean that you
should never find yourself in a position where your data is in danger due to failed backups.
Other useful tools and tipsOther
Pg. 23 useful tools and tips
Coding Standards

Coding Standards
Coding Standards

For PL/SQL

Please follow the following coding conventions.


The best way to write compliant code is to familiarize yourself with the existing code and try to
adapt a similar style.

General
-------

* Files should use Windows line endings. Any decent editor will understand both Windows and
Unix line endings, but by sticking to Windows line endings the files can be viewed without
problems even in "dumb" editors such as Notepad.

Case
----
* All identifiers, built-in functions, packages and other code should be written in lowercase.
* Use underscores between words.
* CORRECT: get_invoice_totals
* WRONG: GET_INVOICE_TOTALS
* WRONG: getInvoiceTotals

Indentation
-----------
* Identation size is 2 spaces
* Do not use tabs, always use spaces

Naming Conventions
------------------
* All packages should be postfixed with _pkg
Other useful tools and tipsOther
Pg. 24 useful tools and tips

* All parameters should be prefixed with p_


* All local variables should be prefixed with l_
* All private "module"-level (ie package body-level) variables should be prefixed with m_
* All public "global" (ie package specification-level) variables should be prefixed with g_
* All public "global" (ie package specification-level) constants should be prefixed with c_ (note:
this is not done consistently in existing code, where constants are commonly prefixed with g_
instead, but new code should use the c_ prefix)

Other
-----
* All program units (functions and procedures) must have a standard comment block that
explains the purpose of the program unit, as well as a change log that includes the author's
initials (max 3 characters), date (using format DD.MM.YYYY) and a description of the change
* All functions must define a local variable called "l_returnvalue" and the last statement in any
function should be "return l_returnvalue;". Do not write functions with multiple return
statements, and do not write procedures with any return statements.
* Always include (repeat) the name of the program unit in the final "end" statement at the end
of the program unit.
* Length of PL/SQL Program unit should not be more than 50 Lines of code
* All complexity of the SQL to be encapsulated in the views and macros to have an easy
and understandable code.
Other useful tools and tipsOther
Pg. 25 useful tools and tips

Notes to User of this Document


For further readings please read articles from

Tim Hall

Steven Feuerstein

Arup Nanda

Ajit Bakshi
Program Manager
[email protected]
m

Company Information
IDBI Intech Pvt. LTD

Learning is lifelong
journy

You might also like