SlideShare a Scribd company logo
Technical Skills Enhancement – PL/SQL Best
practices
Oracle Architecture
Objectives
At the end of this session, you will be able to:
• Understand Oracle Architecture
• Database Buffer Cache
• Shared Pool
• Write better performing queries
Agenda
• Introduction to “Performance Tuning”
• What is a database?
• What is a database instance?
• System Global Area
• Program Global Area
• Database Buffer cache
• Cache Hit Ratio
• Buffer Cache and Full table scan
• Shared Pool
• Avoid Code Repetition
• Use bind variables
• Bind variable peeking
• Avoid hardcoding
• Performance tuning tools
Introduction – SQL and PL/SQL tuning
• Tuning SQL and PL/SQL code is an iterative and
incremental process.
• There is no “Silver Bullet” (Straightforward solution
perceived to have extreme effectiveness)
• Nothing is “Set in stone”. You have to keep up with
technology and continue learning and experimenting.
• Tuning Oracle database programs involves three main
areas :
– SQL statements
– PL/SQL code (Logic, algorithms)
– Memory utilization and management of code
Introduction – SQL and PL/SQL tuning
• Factors affecting performance of a database
90%
60%
Oracle Database Architecture
An Oracle database server consists of a database and at least one
database instance(commonly referred to as simply an instance).
Because an instance and a database are so closely connected, the term
Oracle database is sometimes used to refer to both instance and
database. In the strictest sense the terms have the following meanings:
■ Database
•A database is a set of files, located on disk, that store data. These files
can exist independently of a database instance.
■ Database instance
•An instance is a set of memory structures that manage database files
and user interactions.
•The instance consists of 2 memory areas
– System Global Area (SGA), which is shared by all user, server and
background processes.
– Program Global Areas (PGA), which is private to each user, server and
background process; there is one PGA for each session/process.
Oracle Architecture
System Global Area
The SGA is read/write. If multiple users are concurrently connected to the
same instance, then the data in the instance's SGA is shared among the
users.
The SGA contains the following data structures:
– Database buffer cache
– Redo log buffer
– Shared pool
– Java pool
– Large pool (optional)
– Streams pool
– Other miscellaneous information
System Global Area – Database buffer cache
Function
PGA
System Global Area – Database buffer cache
First access
Subsequent accesses
PGA
Function
Database
2. Not in cache;
Request data
from database
3. Pass Data
to Cache
Application
1. Application
Requests Data
4. Data retrieved
from cache 5. Data returned
to application
Application
1. Application
Requests Data
4. Data returned
to application
3. Data retrieved
from cache
Database
2. Data found in
cache. No need to
read from disk
System Global Area – Cache hit ratio
A properly sized buffer cache can usually yield a cache hit ratio over 90%,
meaning that nine requests out of ten are satisfied without going to disk.
•Designing your program in such a way that queries against a table are
adjacent to each other than spread across the program will ensure better
cache hit ratio.
•Scheduling similar batch jobs together (or next to each other) in the same
time window will also ensure better cache hit ratio. Eg: scheduling “Audit
management” infolets next to each other in the same time window and then
all “Risk management” infolets in the next timeslot will ensure better
performance than mixing them.
•Batch Processes that handle large data set must be scheduled in non-peak
hours to reduce cache misses for regular application users.
System Global Area – Buffer cache and FTS
System Global Area – Buffer cache and FTS
Buffer Cache and Full Table Scan
•When the user process is performing a full table scan, it reads the
blocks of the table into buffers and puts them on the LRU end (instead of
the MRU end) of the LRU list.
•This is because (“Oracle assumes that ”)a fully scanned table usually is
needed only briefly, so the blocks should be moved out quickly to leave
more frequently used blocks in the cache.
•You can control this default behavior of blocks involved in table scans
on a table-by-table basis. To specify that blocks of the table are to be
placed at the MRU end of the list during a full table scan, use
the CACHE clause when creating or altering a table.
CREATE TABLE status_lookup (CODE VARCHAR2(2), DESCRIPTION VARCHAR2(30)) CACHE;
•You can specify this behavior for small lookup tables or static
historical tables to avoid I/O on subsequent accesses of the table.
•This will help improve performance if the table is accessed
frequently.
System Global Area – Shared Pool
System Global Area (SGA)
Shared Pool
show_empscalc_totals upd_salaries
Select *
from emp
Shared SQL
Pre-parsed
Update emp
Set sal=...
Library cache
Session 1 memory
(PGA/UGA)
emp_rec emp%rowtype;
tot_tab tottabtype;
Session 2 memory
(PGA/UGA)
emp_rec emp%rowtype;
tot_tab tottabtype;
User 1
User 2
System Global Area – Shared Pool
Dictionary
Cache
• Oracle saves memory in shared pool by using one shared SQL area
for SQL statements run multiple times. Oracle recognizes when two
users are executing the same SQL statement and reuses the shared
SQL area for those users. The statements have to be EXACTLY the
same including character spacing and character case.
• The below statements are not treated as the same statements by
Oracle
Script: SharedPool.sql
SELECT DUMMY FROM DUAL ;
SELECT DUMMY FROM dual ;
SELECT DUMMY FROM DUAL ;
These statements will be parsed separately and stored separately in
shared pool.
System Global Area – Shared Pool
• For better performance
– Modularize and reuse program units as much as possible.
– Avoid repeating SQL statements. Write once and use many
times.
– Use bind variables
– Avoid hard coding
– Follow coding guidelines, standards and naming conventions in
your project.
– Ensure developers write code the same way. Achieve a
consistent, readable coding style
System Global Area – Shared Pool
– When a snippet of code is repeated across the application, then it is
almost impossible to know/keep track of all the places it occurs. This
becomes especially difficult when code changes have to be
implemented.
– Encapsulate all SQL statements behind a procedural interface, usually a
package.
– Hide all single row queries behind functions
– Hide entire DML statements in procedures, so you can choose (and
change) the implementation for optimal performance
– Use common, standardized exception handling, error and event logging
across the application
– Rely on pre-built, pre-tested, write-once, use-often PL/SQL programs.
These guidelines are aimed at optimizing the use of shared pool.
System Global Area – Shared Pool – Avoid code
repetition
If you have a Java program that does
for (int i=0; i<userArray.length; i++) {
String delQuery = “DELETE FROM si_users WHERE user_id = “ +
userArray[i];
stmt.executeUpdate(delQuery);
}
When executed, this code generates SQL as below. Each
statement has to be parsed separately in
Shared Pool !. Bad Idea !
DELETE FROM si_users WHERE user_id = 100001
DELETE FROM si_users WHERE user_id = 100002
DELETE FROM si_users WHERE user_id = 100003
DELETE FROM si_users WHERE user_id = 100004
DELETE FROM si_users WHERE user_id = 100005
DELETE FROM si_users WHERE user_id = 100006
...
System Global Area – Shared Pool – Use bind
variables
Parsing is
expensive!!!
System Global Area - Use bind variables
It can be rewritten as below-
String delQuery = “DELETE FROM si_users WHERE user_id = ?”;
// Alternatively use
// delQuery = si_users.delete_user(?);
stmt = conn.prepareCall(delQuery);
for (int i=0; i<userArray.length; i++) {
stmt.setInt(1, userArray[i]);
stmt.execute();
}
Inside shared pool
DELETE FROM si_users WHERE user_id = :b1
A very happy database
!!!
System Global Area - Use bind variables
Bind variables in PL/SQL
•The good news is that PL/SQL itself takes care of most of the
issues to do with bind variables, to the point where most code
that you write already uses bind variables without you knowing.
Take, for example, the following bit of PL/SQL:
create or replace procedure updsal(p_empno in
number)
as
begin
update emp
set sal=sal*2
where empno = p_empno;
commit;
end;
/
System Global Area - Use bind variables
Bind variables in PL/SQL
•DO NOT: “where created_date > to_date(’01-sep-
2006’)..”
•BETTER :
v_date := to_date(’01-sep-2006’)
where created_date > v_date “
System Global Area - Use bind variables
Bind variables in Dynamic PL/SQL
Special care must be taken while writing dynamic SQL.
The code below does not use bind variable, instead it builds a new SQL
statement each time concatenating the value in TO_CHAR(i).
Script : BindVariables.sql
DECLARE
l_dummy dual.dummy%TYPE;
BEGIN
FOR i IN 1 .. 10 LOOP
BEGIN
EXECUTE IMMEDIATE 'SELECT dummy FROM dual WHERE dummy = ''' ||
TO_CHAR(i) || ''''
INTO l_dummy;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
END LOOP;
END;
System Global Area - Use bind variables
Using bind variable…..
DECLARE
l_dummy dual.dummy%TYPE;
BEGIN
FOR i IN 1 .. 10 LOOP
BEGIN
EXECUTE IMMEDIATE 'SELECT dummy FROM dual WHERE dummy =
TO_CHAR(:dummy)'
INTO l_dummy USING i;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
END LOOP;
END;
Bind Variable Peeking
• When Oracle sees a brand new query (not yet parsed) with bind variable, in an
effort to choose the best plan Oracle “peeks” at the value of the bind variable
and then chooses the plan accordingly.
• This plan is then utilized for all subsequent runs of the same query.
• This could be beneficial in a good percentage of cases.
• In certain situations this may produce unpredictable results
• A table with 10 million rows. A column has 2 distinct values Y and N. 99% of the
rows contain the value Y and 1% contain the value N. (Skewed data)
• When Y is used (non selective) in the WHERE clause a full table scan would be
the best approach
• When N is used in the WHERE clause an INDEX scan would be best
• If query with Y was run first, it would always perform FTS which will considerably
slow down the application
• If query with N was run first, it would always perform INDEX scan which would
make N queries very fast, but slightly slow down Y queries
Bind Variable Peeking – Cause and effect – On a lighter note
The butterfly effect
In chaos theory , a butterfly
flapping its wings gently in a far
away tropical forest could cause
major hurricanes a few weeks later
in the east coast of United States!!
The Rain effect
There was an application where,
whenever it rains on a Monday
morning - the database had to be
restarted in the afternoon to make it
perform correctly.
*Every Monday morning*, *every
single time* if it rains the DB slows
down. Since the users have
experienced it several 100 times
they would call up the DBA and say-
"It is Monday, it is raining, you know
what to do", after the reboot,
everything is running fast again.
What did Monday morning rain have
to do with DB performance???
Bind Variable Peeking – Cause and effect – On a lighter note
The Rain effect
•The DBAs took backups on Sunday nights emptying the shared pool
•The application had a frequently executed query on a table with
skewed data. The query would run with selective value only for “A
user”. This user lives far away from office. He normally arrived office
at 6am.
•On regular Monday mornings the query would be executed for the first
time (hence hard parsed) for him with selective value. Due to BVP it
would register INDEX scan. INDEX scan it is for all subsequent runs. Not
bad at all.
•On rainy days he comes in late after the rain subsides. If rain happens
to fall on Monday morning while the shared pool is empty, then the
larger user group with non-selective value hits the application first,
registering FTS. FTS it is for all subsequent runs. Bringing the DB to its
knees.
So…… who is the culprit now, the rain or BVP????
Avoid hard coding
Avoid hard coding not only for better performance, but also
for the below reason-
Hard Coding – Someone assumed that something will never
change and that is ne ve r true !!. Avoid hardcoding to reduce
source code impact when requirements change.
•Avoid hard coding literal values
IF num_requests > 100 THEN
IF num_requests > l_limit THEN
•Whenever possible, use anchored declarations rather than
explicit datatype references
VARCHAR2(20);  Hard coded declaration
Tablename.fieldname%type;  Anchored declaration
Tablename%rowtype;  Anchored declaration
Avoid hard coding
Avoid hard coding in cursors. Instead use parameterized cursors. In some cases this
will also facilitate usage of bind variables.
Instead of ….
DECLARE
CURSOR dept_cur IS
SELECT last_name FROM employee
WHERE department_id = 10;
BEGIN
OPEN dept_cur;
Rewrite as below …
DECLARE
CURSOR dept_cur (dept IN INTEGER) IS
SELECT last_name FROM employee
WHERE department_id = dept;
BEGIN
PL/SQL Tuning for performance
Some methods used to measure and analyze performance of PL/SQL
code
• Utilize Oracle’s Tools
– EXPLAIN_PLAN
– Autotrace
– V$SQLAREA
– AWR/ADDM report …….
• Third party tools
– Quest SQLab,
– Quest Spotlight,
– Computer Associates SQL Station Plan Analyzer .......
• Homegrown utilities
– Timer Utility for procedures
– SMC
• Code reviews
• Load Testing
PL/SQL Tuning for performance
• Explain Plan
• Whenever an SQL statement is run, Oracle parses and analyzes the
query to find the most effective way to execute the query and then
designs an execution plan for it.
• This execution plan is basically a step by step instruction for how the
statement must be executed. That is, the order in which the tables are
read, if indexes are used, which join methods are used to join tables
and so on.
It shows the following information:
• Ordering of the tables referenced by the statement
• Access method for each table mentioned in the statement
• Join method for tables affected by join operations in the statement
• Data operations like filter, sort, or aggregation
• Cost and Cardinality of each operation
Performance Tuning Best practices – Explain plan
Understanding the execution plan –
•Cost - The estimated resource usage for that plan. The lower the
cost the more efficient the plan is expected to be. The optimizer’s
cost model accounts for the I/O, CPU and network resources that
will be used by the query.
•Cardinality– Estimate of the number of rows coming out of each of
the operations.
•Access method – The way in which the data is being accessed,
via either a table scan or index access. Eg: Full table scan, table
access by ROWID, Index unique scan, Index range scan etc
•Join method – The method (e.g., hash, nested loops, sort-merge,
etc.) used to join tables with each other.
PL/SQL Tuning for performance
• Sample execution plan
PL/SQL Tuning for performance
Autotrace :
•In SQL*Plus you can automatically get a report on the execution path
used by the SQL optimizer and the statement execution statistics. The
report is generated after a successful SQL DML statement, such as
SELECT, DELETE, UPDATE or INSERT. It is useful for monitoring and
tuning the performance of these DML statements.
Thank You
Feedback, Questions, Discussion

More Related Content

What's hot

Oracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuningOracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuning
Smitha Padmanabhan
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuningSimon Huang
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle Architecture
Neeraj Singh
 
Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle databaseSamar Prasad
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
Guy Harrison
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture ppt
Deepak Shetty
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
Enkitec
 
Less08 users
Less08 usersLess08 users
Less08 users
Amit Bhalla
 
Oracle db architecture
Oracle db architectureOracle db architecture
Oracle db architectureSimon Huang
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
Chien Chung Shen
 
Oracle database hot backup and recovery
Oracle database hot backup and recoveryOracle database hot backup and recovery
Oracle database hot backup and recovery
Arun Sharma
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
SrirakshaSrinivasan2
 
Understanding oracle rac internals part 2 - slides
Understanding oracle rac internals   part 2 - slidesUnderstanding oracle rac internals   part 2 - slides
Understanding oracle rac internals part 2 - slides
Mohamed Farouk
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architectureAmit Bhalla
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switching
Smitha Padmanabhan
 
Understanding oracle rac internals part 1 - slides
Understanding oracle rac internals   part 1 - slidesUnderstanding oracle rac internals   part 1 - slides
Understanding oracle rac internals part 1 - slides
Mohamed Farouk
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
Amrit Kaur
 

What's hot (20)

Data guard oracle
Data guard oracleData guard oracle
Data guard oracle
 
Oracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuningOracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuning
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle Architecture
 
Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle database
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture ppt
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
Less08 users
Less08 usersLess08 users
Less08 users
 
Oracle db architecture
Oracle db architectureOracle db architecture
Oracle db architecture
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 
Oracle database hot backup and recovery
Oracle database hot backup and recoveryOracle database hot backup and recovery
Oracle database hot backup and recovery
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
 
Understanding oracle rac internals part 2 - slides
Understanding oracle rac internals   part 2 - slidesUnderstanding oracle rac internals   part 2 - slides
Understanding oracle rac internals part 2 - slides
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
 
Lecture2 oracle ppt
Lecture2 oracle pptLecture2 oracle ppt
Lecture2 oracle ppt
 
Resize sga
Resize sgaResize sga
Resize sga
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switching
 
Understanding oracle rac internals part 1 - slides
Understanding oracle rac internals   part 1 - slidesUnderstanding oracle rac internals   part 1 - slides
Understanding oracle rac internals part 1 - slides
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
 

Viewers also liked

A4 oracle's application engineered storage your application advantage
A4   oracle's application engineered storage your application advantageA4   oracle's application engineered storage your application advantage
A4 oracle's application engineered storage your application advantageDr. Wilfred Lin (Ph.D.)
 
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloudC6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
Dr. Wilfred Lin (Ph.D.)
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
Smitha Padmanabhan
 
Oracle Cloud Reference Architecture
Oracle Cloud Reference ArchitectureOracle Cloud Reference Architecture
Oracle Cloud Reference Architecture
Bob Rhubart
 
Oracle Database Backup Cloud Service
Oracle Database Backup Cloud ServiceOracle Database Backup Cloud Service
Oracle Database Backup Cloud Service
MarketingArrowECS_CZ
 
Présentation Oracle DataBase 11g
Présentation Oracle DataBase 11gPrésentation Oracle DataBase 11g
Présentation Oracle DataBase 11g
Cynapsys It Hotspot
 
Oracle database 12c sql worshop 1 student guide vol 2
Oracle database 12c sql worshop 1 student guide vol 2Oracle database 12c sql worshop 1 student guide vol 2
Oracle database 12c sql worshop 1 student guide vol 2
Otto Paiz
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overviewhonglee71
 

Viewers also liked (8)

A4 oracle's application engineered storage your application advantage
A4   oracle's application engineered storage your application advantageA4   oracle's application engineered storage your application advantage
A4 oracle's application engineered storage your application advantage
 
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloudC6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
C6 oracles storage_strategy_from_databases_to_engineered_systems_to_cloud
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
 
Oracle Cloud Reference Architecture
Oracle Cloud Reference ArchitectureOracle Cloud Reference Architecture
Oracle Cloud Reference Architecture
 
Oracle Database Backup Cloud Service
Oracle Database Backup Cloud ServiceOracle Database Backup Cloud Service
Oracle Database Backup Cloud Service
 
Présentation Oracle DataBase 11g
Présentation Oracle DataBase 11gPrésentation Oracle DataBase 11g
Présentation Oracle DataBase 11g
 
Oracle database 12c sql worshop 1 student guide vol 2
Oracle database 12c sql worshop 1 student guide vol 2Oracle database 12c sql worshop 1 student guide vol 2
Oracle database 12c sql worshop 1 student guide vol 2
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 

Similar to 01 oracle architecture

The Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result CacheThe Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result Cache
Steven Feuerstein
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
Antonios Chatzipavlis
 
שבוע אורקל 2016
שבוע אורקל 2016שבוע אורקל 2016
שבוע אורקל 2016Aaron Shilo
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Aaron Shilo
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Steven Feuerstein
 
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
Markus Michalewicz
 
OOW09 Ebs Tuning Final
OOW09 Ebs Tuning FinalOOW09 Ebs Tuning Final
OOW09 Ebs Tuning Finaljucaab
 
Snowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
Snowflake_Cheat_Sheet_Snowflake_Cheat_SheetSnowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
Snowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
haripra2
 
MOUG17: SQLT Utility for Tuning - Practical Examples
MOUG17: SQLT Utility for Tuning - Practical ExamplesMOUG17: SQLT Utility for Tuning - Practical Examples
MOUG17: SQLT Utility for Tuning - Practical Examples
Monica Li
 
MOUG17: DB Security; Secure your Data
MOUG17: DB Security; Secure your DataMOUG17: DB Security; Secure your Data
MOUG17: DB Security; Secure your Data
Monica Li
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous Database
Sandesh Rao
 
Investigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock HolmesInvestigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock Holmes
Richard Douglas
 
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_DatabaseNoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_DatabaseParesh Patel
 
Dal deck
Dal deckDal deck
Dal deck
Caroline_Rose
 
Distributed Performance testing by funkload
Distributed Performance testing by funkloadDistributed Performance testing by funkload
Distributed Performance testing by funkload
Akhil Singh
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for AndroidJakir Hossain
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001jucaab
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
Ihor Bobak
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptx
LemonReddy1
 

Similar to 01 oracle architecture (20)

The Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result CacheThe Amazing and Elegant PL/SQL Function Result Cache
The Amazing and Elegant PL/SQL Function Result Cache
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
 
שבוע אורקל 2016
שבוע אורקל 2016שבוע אורקל 2016
שבוע אורקל 2016
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk Processing
 
les12.pdf
les12.pdfles12.pdf
les12.pdf
 
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
AskTom: How to Make and Test Your Application "Oracle RAC Ready"?
 
OOW09 Ebs Tuning Final
OOW09 Ebs Tuning FinalOOW09 Ebs Tuning Final
OOW09 Ebs Tuning Final
 
Snowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
Snowflake_Cheat_Sheet_Snowflake_Cheat_SheetSnowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
Snowflake_Cheat_Sheet_Snowflake_Cheat_Sheet
 
MOUG17: SQLT Utility for Tuning - Practical Examples
MOUG17: SQLT Utility for Tuning - Practical ExamplesMOUG17: SQLT Utility for Tuning - Practical Examples
MOUG17: SQLT Utility for Tuning - Practical Examples
 
MOUG17: DB Security; Secure your Data
MOUG17: DB Security; Secure your DataMOUG17: DB Security; Secure your Data
MOUG17: DB Security; Secure your Data
 
Top 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous DatabaseTop 20 FAQs on the Autonomous Database
Top 20 FAQs on the Autonomous Database
 
Investigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock HolmesInvestigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock Holmes
 
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_DatabaseNoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
NoCOUG_201411_Patel_Managing_a_Large_OLTP_Database
 
Dal deck
Dal deckDal deck
Dal deck
 
Distributed Performance testing by funkload
Distributed Performance testing by funkloadDistributed Performance testing by funkload
Distributed Performance testing by funkload
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptx
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 

Recently uploaded (20)

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 

01 oracle architecture

  • 1. Technical Skills Enhancement – PL/SQL Best practices Oracle Architecture
  • 2. Objectives At the end of this session, you will be able to: • Understand Oracle Architecture • Database Buffer Cache • Shared Pool • Write better performing queries
  • 3. Agenda • Introduction to “Performance Tuning” • What is a database? • What is a database instance? • System Global Area • Program Global Area • Database Buffer cache • Cache Hit Ratio • Buffer Cache and Full table scan • Shared Pool • Avoid Code Repetition • Use bind variables • Bind variable peeking • Avoid hardcoding • Performance tuning tools
  • 4. Introduction – SQL and PL/SQL tuning • Tuning SQL and PL/SQL code is an iterative and incremental process. • There is no “Silver Bullet” (Straightforward solution perceived to have extreme effectiveness) • Nothing is “Set in stone”. You have to keep up with technology and continue learning and experimenting. • Tuning Oracle database programs involves three main areas : – SQL statements – PL/SQL code (Logic, algorithms) – Memory utilization and management of code
  • 5. Introduction – SQL and PL/SQL tuning • Factors affecting performance of a database 90% 60%
  • 6. Oracle Database Architecture An Oracle database server consists of a database and at least one database instance(commonly referred to as simply an instance). Because an instance and a database are so closely connected, the term Oracle database is sometimes used to refer to both instance and database. In the strictest sense the terms have the following meanings: ■ Database •A database is a set of files, located on disk, that store data. These files can exist independently of a database instance. ■ Database instance •An instance is a set of memory structures that manage database files and user interactions. •The instance consists of 2 memory areas – System Global Area (SGA), which is shared by all user, server and background processes. – Program Global Areas (PGA), which is private to each user, server and background process; there is one PGA for each session/process.
  • 8. System Global Area The SGA is read/write. If multiple users are concurrently connected to the same instance, then the data in the instance's SGA is shared among the users. The SGA contains the following data structures: – Database buffer cache – Redo log buffer – Shared pool – Java pool – Large pool (optional) – Streams pool – Other miscellaneous information
  • 9. System Global Area – Database buffer cache
  • 10. Function PGA System Global Area – Database buffer cache First access Subsequent accesses PGA Function Database 2. Not in cache; Request data from database 3. Pass Data to Cache Application 1. Application Requests Data 4. Data retrieved from cache 5. Data returned to application Application 1. Application Requests Data 4. Data returned to application 3. Data retrieved from cache Database 2. Data found in cache. No need to read from disk
  • 11. System Global Area – Cache hit ratio A properly sized buffer cache can usually yield a cache hit ratio over 90%, meaning that nine requests out of ten are satisfied without going to disk. •Designing your program in such a way that queries against a table are adjacent to each other than spread across the program will ensure better cache hit ratio. •Scheduling similar batch jobs together (or next to each other) in the same time window will also ensure better cache hit ratio. Eg: scheduling “Audit management” infolets next to each other in the same time window and then all “Risk management” infolets in the next timeslot will ensure better performance than mixing them. •Batch Processes that handle large data set must be scheduled in non-peak hours to reduce cache misses for regular application users.
  • 12. System Global Area – Buffer cache and FTS
  • 13. System Global Area – Buffer cache and FTS Buffer Cache and Full Table Scan •When the user process is performing a full table scan, it reads the blocks of the table into buffers and puts them on the LRU end (instead of the MRU end) of the LRU list. •This is because (“Oracle assumes that ”)a fully scanned table usually is needed only briefly, so the blocks should be moved out quickly to leave more frequently used blocks in the cache. •You can control this default behavior of blocks involved in table scans on a table-by-table basis. To specify that blocks of the table are to be placed at the MRU end of the list during a full table scan, use the CACHE clause when creating or altering a table. CREATE TABLE status_lookup (CODE VARCHAR2(2), DESCRIPTION VARCHAR2(30)) CACHE; •You can specify this behavior for small lookup tables or static historical tables to avoid I/O on subsequent accesses of the table. •This will help improve performance if the table is accessed frequently.
  • 14. System Global Area – Shared Pool
  • 15. System Global Area (SGA) Shared Pool show_empscalc_totals upd_salaries Select * from emp Shared SQL Pre-parsed Update emp Set sal=... Library cache Session 1 memory (PGA/UGA) emp_rec emp%rowtype; tot_tab tottabtype; Session 2 memory (PGA/UGA) emp_rec emp%rowtype; tot_tab tottabtype; User 1 User 2 System Global Area – Shared Pool Dictionary Cache
  • 16. • Oracle saves memory in shared pool by using one shared SQL area for SQL statements run multiple times. Oracle recognizes when two users are executing the same SQL statement and reuses the shared SQL area for those users. The statements have to be EXACTLY the same including character spacing and character case. • The below statements are not treated as the same statements by Oracle Script: SharedPool.sql SELECT DUMMY FROM DUAL ; SELECT DUMMY FROM dual ; SELECT DUMMY FROM DUAL ; These statements will be parsed separately and stored separately in shared pool. System Global Area – Shared Pool
  • 17. • For better performance – Modularize and reuse program units as much as possible. – Avoid repeating SQL statements. Write once and use many times. – Use bind variables – Avoid hard coding – Follow coding guidelines, standards and naming conventions in your project. – Ensure developers write code the same way. Achieve a consistent, readable coding style System Global Area – Shared Pool
  • 18. – When a snippet of code is repeated across the application, then it is almost impossible to know/keep track of all the places it occurs. This becomes especially difficult when code changes have to be implemented. – Encapsulate all SQL statements behind a procedural interface, usually a package. – Hide all single row queries behind functions – Hide entire DML statements in procedures, so you can choose (and change) the implementation for optimal performance – Use common, standardized exception handling, error and event logging across the application – Rely on pre-built, pre-tested, write-once, use-often PL/SQL programs. These guidelines are aimed at optimizing the use of shared pool. System Global Area – Shared Pool – Avoid code repetition
  • 19. If you have a Java program that does for (int i=0; i<userArray.length; i++) { String delQuery = “DELETE FROM si_users WHERE user_id = “ + userArray[i]; stmt.executeUpdate(delQuery); } When executed, this code generates SQL as below. Each statement has to be parsed separately in Shared Pool !. Bad Idea ! DELETE FROM si_users WHERE user_id = 100001 DELETE FROM si_users WHERE user_id = 100002 DELETE FROM si_users WHERE user_id = 100003 DELETE FROM si_users WHERE user_id = 100004 DELETE FROM si_users WHERE user_id = 100005 DELETE FROM si_users WHERE user_id = 100006 ... System Global Area – Shared Pool – Use bind variables Parsing is expensive!!!
  • 20. System Global Area - Use bind variables It can be rewritten as below- String delQuery = “DELETE FROM si_users WHERE user_id = ?”; // Alternatively use // delQuery = si_users.delete_user(?); stmt = conn.prepareCall(delQuery); for (int i=0; i<userArray.length; i++) { stmt.setInt(1, userArray[i]); stmt.execute(); } Inside shared pool DELETE FROM si_users WHERE user_id = :b1 A very happy database !!!
  • 21. System Global Area - Use bind variables Bind variables in PL/SQL •The good news is that PL/SQL itself takes care of most of the issues to do with bind variables, to the point where most code that you write already uses bind variables without you knowing. Take, for example, the following bit of PL/SQL: create or replace procedure updsal(p_empno in number) as begin update emp set sal=sal*2 where empno = p_empno; commit; end; /
  • 22. System Global Area - Use bind variables Bind variables in PL/SQL •DO NOT: “where created_date > to_date(’01-sep- 2006’)..” •BETTER : v_date := to_date(’01-sep-2006’) where created_date > v_date “
  • 23. System Global Area - Use bind variables Bind variables in Dynamic PL/SQL Special care must be taken while writing dynamic SQL. The code below does not use bind variable, instead it builds a new SQL statement each time concatenating the value in TO_CHAR(i). Script : BindVariables.sql DECLARE l_dummy dual.dummy%TYPE; BEGIN FOR i IN 1 .. 10 LOOP BEGIN EXECUTE IMMEDIATE 'SELECT dummy FROM dual WHERE dummy = ''' || TO_CHAR(i) || '''' INTO l_dummy; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; END; END LOOP; END;
  • 24. System Global Area - Use bind variables Using bind variable….. DECLARE l_dummy dual.dummy%TYPE; BEGIN FOR i IN 1 .. 10 LOOP BEGIN EXECUTE IMMEDIATE 'SELECT dummy FROM dual WHERE dummy = TO_CHAR(:dummy)' INTO l_dummy USING i; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; END; END LOOP; END;
  • 25. Bind Variable Peeking • When Oracle sees a brand new query (not yet parsed) with bind variable, in an effort to choose the best plan Oracle “peeks” at the value of the bind variable and then chooses the plan accordingly. • This plan is then utilized for all subsequent runs of the same query. • This could be beneficial in a good percentage of cases. • In certain situations this may produce unpredictable results • A table with 10 million rows. A column has 2 distinct values Y and N. 99% of the rows contain the value Y and 1% contain the value N. (Skewed data) • When Y is used (non selective) in the WHERE clause a full table scan would be the best approach • When N is used in the WHERE clause an INDEX scan would be best • If query with Y was run first, it would always perform FTS which will considerably slow down the application • If query with N was run first, it would always perform INDEX scan which would make N queries very fast, but slightly slow down Y queries
  • 26. Bind Variable Peeking – Cause and effect – On a lighter note The butterfly effect In chaos theory , a butterfly flapping its wings gently in a far away tropical forest could cause major hurricanes a few weeks later in the east coast of United States!! The Rain effect There was an application where, whenever it rains on a Monday morning - the database had to be restarted in the afternoon to make it perform correctly. *Every Monday morning*, *every single time* if it rains the DB slows down. Since the users have experienced it several 100 times they would call up the DBA and say- "It is Monday, it is raining, you know what to do", after the reboot, everything is running fast again. What did Monday morning rain have to do with DB performance???
  • 27. Bind Variable Peeking – Cause and effect – On a lighter note The Rain effect •The DBAs took backups on Sunday nights emptying the shared pool •The application had a frequently executed query on a table with skewed data. The query would run with selective value only for “A user”. This user lives far away from office. He normally arrived office at 6am. •On regular Monday mornings the query would be executed for the first time (hence hard parsed) for him with selective value. Due to BVP it would register INDEX scan. INDEX scan it is for all subsequent runs. Not bad at all. •On rainy days he comes in late after the rain subsides. If rain happens to fall on Monday morning while the shared pool is empty, then the larger user group with non-selective value hits the application first, registering FTS. FTS it is for all subsequent runs. Bringing the DB to its knees. So…… who is the culprit now, the rain or BVP????
  • 28. Avoid hard coding Avoid hard coding not only for better performance, but also for the below reason- Hard Coding – Someone assumed that something will never change and that is ne ve r true !!. Avoid hardcoding to reduce source code impact when requirements change. •Avoid hard coding literal values IF num_requests > 100 THEN IF num_requests > l_limit THEN •Whenever possible, use anchored declarations rather than explicit datatype references VARCHAR2(20);  Hard coded declaration Tablename.fieldname%type;  Anchored declaration Tablename%rowtype;  Anchored declaration
  • 29. Avoid hard coding Avoid hard coding in cursors. Instead use parameterized cursors. In some cases this will also facilitate usage of bind variables. Instead of …. DECLARE CURSOR dept_cur IS SELECT last_name FROM employee WHERE department_id = 10; BEGIN OPEN dept_cur; Rewrite as below … DECLARE CURSOR dept_cur (dept IN INTEGER) IS SELECT last_name FROM employee WHERE department_id = dept; BEGIN
  • 30. PL/SQL Tuning for performance Some methods used to measure and analyze performance of PL/SQL code • Utilize Oracle’s Tools – EXPLAIN_PLAN – Autotrace – V$SQLAREA – AWR/ADDM report ……. • Third party tools – Quest SQLab, – Quest Spotlight, – Computer Associates SQL Station Plan Analyzer ....... • Homegrown utilities – Timer Utility for procedures – SMC • Code reviews • Load Testing
  • 31. PL/SQL Tuning for performance • Explain Plan • Whenever an SQL statement is run, Oracle parses and analyzes the query to find the most effective way to execute the query and then designs an execution plan for it. • This execution plan is basically a step by step instruction for how the statement must be executed. That is, the order in which the tables are read, if indexes are used, which join methods are used to join tables and so on. It shows the following information: • Ordering of the tables referenced by the statement • Access method for each table mentioned in the statement • Join method for tables affected by join operations in the statement • Data operations like filter, sort, or aggregation • Cost and Cardinality of each operation
  • 32. Performance Tuning Best practices – Explain plan Understanding the execution plan – •Cost - The estimated resource usage for that plan. The lower the cost the more efficient the plan is expected to be. The optimizer’s cost model accounts for the I/O, CPU and network resources that will be used by the query. •Cardinality– Estimate of the number of rows coming out of each of the operations. •Access method – The way in which the data is being accessed, via either a table scan or index access. Eg: Full table scan, table access by ROWID, Index unique scan, Index range scan etc •Join method – The method (e.g., hash, nested loops, sort-merge, etc.) used to join tables with each other.
  • 33. PL/SQL Tuning for performance • Sample execution plan
  • 34. PL/SQL Tuning for performance Autotrace : •In SQL*Plus you can automatically get a report on the execution path used by the SQL optimizer and the statement execution statistics. The report is generated after a successful SQL DML statement, such as SELECT, DELETE, UPDATE or INSERT. It is useful for monitoring and tuning the performance of these DML statements.