Oracle Tips and Tricks
Oracle Tips and Tricks
Tips and
Tricks
BY AJIT BAKSHI
To understand anything we must have an open mind
Table of Contents
Oracle Database Details________________________________________________________1
Instance Details_____________________________________________________________1
Tablespace Details__________________________________________________________1
User Details________________________________________________________________2
Server Details______________________________________________________________2
Auto addition of Partition to table and compression on Tablespace level and Table level____6
Pragma UDF______________________________________________________________12
NOCOPY Hint to Improve Performance of OUT and IN OUT Parameters in PL/SQL Code_13
Performance Tuning__________________________________________________________15
What to look for____________________________________________________________15
Techniques/Tools to use_____________________________________________________15
Example_________________________________________________________________16
Take database backup to remote database for selected tables using EXPDP____________18
RMAN Backups____________________________________________________________21
Coding Standards____________________________________________________________22
For PL/SQL_______________________________________________________________22
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
*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
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
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
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
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.
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.
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.
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
For example:-
select count(1)
from alr
where acct_label in (select acct_label_code from alc where substr(acct_label_code,1,2) =
'BC');
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).
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:
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');
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.
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
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 );
-- .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 ;
COMMIT;
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
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
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.
$ mkdir /home/oracle/wallet
$ cd /home/oracle/wallet
$ export PATH=$PATH:$ORACLE_HOME/bin
5) You can check the contents of the wallet with the following command.
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
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
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
Tim Hall
Steven Feuerstein
Arup Nanda
Ajit Bakshi
Program Manager
[email protected]
m
Company Information
IDBI Intech Pvt. LTD
Learning is lifelong
journy