SlideShare ist ein Scribd-Unternehmen logo
1 von 52
High Performance PL/SQL Guy Harrison Director of Development, Melbourne www.guyharrison.net
Introductions  Buy Guy’s Book Buy Quest Products
http://www.motivatedphotos.com/?id=17760
Measuring PL/SQL performance DBMS_PROFILER is the best way to find PL/SQL “hot spots”:
Scripts at www.guyharrison.net
Toad Profiler support
SQL*Navigator profiler support
11g Hierarchical profiler $ plshprof -output hprof demo1.trc
Plshprof output
DBMS_HPROF tables  Scripts at www.guyharrison.net
When is PL/SQL faster? PL/SQL routines most massively outperform other languages when network round trips are significant.
Network traffic Routines that process large numbers of rows and return simple aggregates are also candidates for a stored procedure approach
Stored procedure alternative
Network traffic example
Aspects of PL/SQL performance
PLSQL_OPTIMIZE_LEVEL
It’s usually the SQL  Most PL/SQL routines spend most of their time executing SELECT statements and DML SQL tuning is a big topic but: Measure SQL overhead of PL/SQL routines first Ensure best possible optimizer statistics  Consider adequacy of indexing Learn how to use DBMS_XPLAN, SQL Trace, etc  Exploit 10g/11g tuning facilities (if licensed) Don’t issue SQL when you don’t need to
SQL or PL/SQL? Scripts at www.guyharrison.net
Three ways of processing rows  Four Memory Requirements CPU & logical reads
One at a time
All at once
In batches
Array processing Bulk collect without LIMIT No bulk collect  (Prior to 10g or PLSQL_OPTIMIZE_LEVEL <2)
Array processing PLSQL_OPTIMIZE_LEVEL>1 causes transparent BULK COLLECT LIMIT 100 Bulk collect without LIMIT No bulk collect  10g or higher with PLSQL_OPTIMIZE_LEVEL >1
BULK COLLECT worst case scenario
Bind variables in Dynamic SQL  Using bind variables allows sharable SQL, reduces parse overhead and minimizes latch contention  Unlike other languages, PL/SQL uses bind variables transparently EXCEPT when using  Dynamic SQL:
Using bind variables
Bind variable performance  10,000 calls
NOCOPY The NOCOPY clause causes a parameter to be passed “by reference” rather than “by value”
NOCOPY performance gains 4,000 row, 10 column “table”;  4000 lookups:
Associative arrays  Traditionally, sequential scans of PLSQL tables are used for caching database table data:
Associative arrays Associative arrays allow for faster and simpler lookups:
Associative array performance 10,000 random customer lookups with 55,000 customers
Reduce unnecessary Looping Unnecessary loop iterations burn CPU
Remove loop Invariant terms Any term in a loop that does not vary should be extracted from the loop PLSQL_OPTIMIZE_LEVEL>1 does this automatically
Loop invariant performance improvements
Recursion (see: recursion) Recursive routines often offer elegant solutions*. However, deep recursion is memory-intensive and usually not scalable * * Known In Australia as “smart-ass solutions”
Recursion memory overhead
Number crunching (1)
Number crunching (2)
11g Function cache Suits deterministic but expensive functions Expensive table lookups on non-volatile tables
Function cache performance  100 executions, random date ranges 1-30 days:
In-lining Manual in-lining Modular design
Automatic in-lining PLSQL_OPTIMIZE_LEVEL = 3 OR:
Ran out of time for... Array insert using FORALL Explicit vs. implicit cursors  RETURNING clause  Pipelined functions Optimizing triggers Short circuit evaluations IF and CASE comparison ordering
Thank You – Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Oracle Database 12c "New features"
Oracle Database 12c "New features" Oracle Database 12c "New features"
Oracle Database 12c "New features"
Anar Godjaev
 

Was ist angesagt? (20)

Oracle Data Redaction - EOUC
Oracle Data Redaction - EOUCOracle Data Redaction - EOUC
Oracle Data Redaction - EOUC
 
Ogh Ace Case, Part 1 and 2, Oracle Xml Database, Marco Gralike
Ogh Ace Case, Part 1 and 2, Oracle Xml Database, Marco GralikeOgh Ace Case, Part 1 and 2, Oracle Xml Database, Marco Gralike
Ogh Ace Case, Part 1 and 2, Oracle Xml Database, Marco Gralike
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expre...
Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expre...Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expre...
Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expre...
 
JAXB
JAXBJAXB
JAXB
 
Oracle Database 12c - Features for Big Data
Oracle Database 12c - Features for Big DataOracle Database 12c - Features for Big Data
Oracle Database 12c - Features for Big Data
 
Oracle Database 12c "New features"
Oracle Database 12c "New features" Oracle Database 12c "New features"
Oracle Database 12c "New features"
 
Oracle’ın parallel execution yetenekleri ve performans
Oracle’ın parallel execution yetenekleri ve performansOracle’ın parallel execution yetenekleri ve performans
Oracle’ın parallel execution yetenekleri ve performans
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
 
Oracle Database Performance Tuning: The Not SQL Option
Oracle Database Performance Tuning: The Not SQL OptionOracle Database Performance Tuning: The Not SQL Option
Oracle Database Performance Tuning: The Not SQL Option
 
Design Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will PerformDesign Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will Perform
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitUltimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
 
Liquibase
LiquibaseLiquibase
Liquibase
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
Crating a Robust Performance Strategy
Crating a Robust Performance StrategyCrating a Robust Performance Strategy
Crating a Robust Performance Strategy
 
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
Best New Features of Oracle Database 12c
Best New Features of Oracle Database 12cBest New Features of Oracle Database 12c
Best New Features of Oracle Database 12c
 
Java 9 sneak peek
Java 9 sneak peekJava 9 sneak peek
Java 9 sneak peek
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
 

Andere mochten auch

PLSQL Developer tips and tricks
PLSQL Developer tips and tricksPLSQL Developer tips and tricks
PLSQL Developer tips and tricks
Patrick Barel
 
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEXLOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
Enkitec
 

Andere mochten auch (20)

Tips and tricks to optimiza SQL Server Backup and Restore
Tips and tricks to optimiza SQL Server Backup and RestoreTips and tricks to optimiza SQL Server Backup and Restore
Tips and tricks to optimiza SQL Server Backup and Restore
 
Programming Motherfucker
Programming MotherfuckerProgramming Motherfucker
Programming Motherfucker
 
Identification of Performance Problems without the Diagnostic Pack
Identification of Performance Problems without the Diagnostic PackIdentification of Performance Problems without the Diagnostic Pack
Identification of Performance Problems without the Diagnostic Pack
 
PLSQL Developer tips and tricks
PLSQL Developer tips and tricksPLSQL Developer tips and tricks
PLSQL Developer tips and tricks
 
Xenogenetics for PL/SQL - infusing with Java best practices
Xenogenetics for PL/SQL - infusing with Java best practicesXenogenetics for PL/SQL - infusing with Java best practices
Xenogenetics for PL/SQL - infusing with Java best practices
 
PLSQL Practices
PLSQL PracticesPLSQL Practices
PLSQL Practices
 
Oracle SQL Developer Top 10 Tips & Tricks
Oracle SQL Developer Top 10 Tips & TricksOracle SQL Developer Top 10 Tips & Tricks
Oracle SQL Developer Top 10 Tips & Tricks
 
AMIS - Can collections speed up your PL/SQL?
AMIS - Can collections speed up your PL/SQL?AMIS - Can collections speed up your PL/SQL?
AMIS - Can collections speed up your PL/SQL?
 
APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !APEX Developers : Do More With LESS !
APEX Developers : Do More With LESS !
 
Troubleshooting APEX Performance Issues
Troubleshooting APEX Performance IssuesTroubleshooting APEX Performance Issues
Troubleshooting APEX Performance Issues
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switching
 
Automated testing APEX Applications
Automated testing APEX ApplicationsAutomated testing APEX Applications
Automated testing APEX Applications
 
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEXLOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEX
 
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
 
PLSQL Standards and Best Practices
PLSQL Standards and Best PracticesPLSQL Standards and Best Practices
PLSQL Standards and Best Practices
 
Generic collection types in PLSQL
Generic collection types in PLSQLGeneric collection types in PLSQL
Generic collection types in PLSQL
 
Striving for Perfection: The Ultimate APEX Application Architecture
Striving for Perfection: The Ultimate APEX Application ArchitectureStriving for Perfection: The Ultimate APEX Application Architecture
Striving for Perfection: The Ultimate APEX Application Architecture
 
Advanced PLSQL Optimizing for Better Performance
Advanced PLSQL Optimizing for Better PerformanceAdvanced PLSQL Optimizing for Better Performance
Advanced PLSQL Optimizing for Better Performance
 
Oracle Text in APEX
Oracle Text in APEXOracle Text in APEX
Oracle Text in APEX
 

Ähnlich wie High Performance Plsql

Exploring plsql new features best practices september 2013
Exploring plsql new features best practices   september 2013Exploring plsql new features best practices   september 2013
Exploring plsql new features best practices september 2013
Andrejs Vorobjovs
 
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AGOLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
Lucidworks
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part i
sqlserver.co.il
 
SQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
SQL Analytics for Search Engineers - Timothy Potter, LucidworksngineersSQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
SQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
Lucidworks
 

Ähnlich wie High Performance Plsql (20)

Exploring plsql new features best practices september 2013
Exploring plsql new features best practices   september 2013Exploring plsql new features best practices   september 2013
Exploring plsql new features best practices september 2013
 
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AGOLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
OLAP Battle - SolrCloud vs. HBase: Presented by Dragan Milosevic, Zanox AG
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
 
Emerging technologies /frameworks in Big Data
Emerging technologies /frameworks in Big DataEmerging technologies /frameworks in Big Data
Emerging technologies /frameworks in Big Data
 
10 sql tips
10 sql tips10 sql tips
10 sql tips
 
Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...Natural Language to SQL Query conversion using Machine Learning Techniques on...
Natural Language to SQL Query conversion using Machine Learning Techniques on...
 
Online Analytical Processing
Online Analytical ProcessingOnline Analytical Processing
Online Analytical Processing
 
Neo4j 3.2 Launch
Neo4j 3.2 LaunchNeo4j 3.2 Launch
Neo4j 3.2 Launch
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
 
Steps to Building a Streaming ETL Pipeline with Apache Kafka® and KSQL
Steps to Building a Streaming ETL Pipeline with Apache Kafka® and KSQLSteps to Building a Streaming ETL Pipeline with Apache Kafka® and KSQL
Steps to Building a Streaming ETL Pipeline with Apache Kafka® and KSQL
 
Harnessing the power of both worlds
Harnessing the power of both worldsHarnessing the power of both worlds
Harnessing the power of both worlds
 
GraphQL-PHP: Dos and don'ts
GraphQL-PHP: Dos and don'tsGraphQL-PHP: Dos and don'ts
GraphQL-PHP: Dos and don'ts
 
Adapting and adopting spm v04
Adapting and adopting spm v04Adapting and adopting spm v04
Adapting and adopting spm v04
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part i
 
SQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
SQL Analytics for Search Engineers - Timothy Potter, LucidworksngineersSQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
SQL Analytics for Search Engineers - Timothy Potter, Lucidworksngineers
 
Expressive Querying of Semantic Databases with Incremental Query Rewriting
Expressive Querying of Semantic Databases with Incremental Query RewritingExpressive Querying of Semantic Databases with Incremental Query Rewriting
Expressive Querying of Semantic Databases with Incremental Query Rewriting
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming Languages
 
Database part2-
Database part2-Database part2-
Database part2-
 
Survey of High Performance NoSQL Systems
Survey of High Performance NoSQL SystemsSurvey of High Performance NoSQL Systems
Survey of High Performance NoSQL Systems
 

Mehr von Guy Harrison

Mega trends in information management
Mega trends in information managementMega trends in information management
Mega trends in information management
Guy Harrison
 
Big datacamp2013 share
Big datacamp2013 shareBig datacamp2013 share
Big datacamp2013 share
Guy Harrison
 
Next generation databases july2010
Next generation databases july2010Next generation databases july2010
Next generation databases july2010
Guy Harrison
 

Mehr von Guy Harrison (20)

Five database trends - updated April 2015
Five database trends - updated April 2015Five database trends - updated April 2015
Five database trends - updated April 2015
 
From oracle to hadoop with Sqoop and other tools
From oracle to hadoop with Sqoop and other toolsFrom oracle to hadoop with Sqoop and other tools
From oracle to hadoop with Sqoop and other tools
 
Thriving and surviving the Big Data revolution
Thriving and surviving the Big Data revolutionThriving and surviving the Big Data revolution
Thriving and surviving the Big Data revolution
 
Mega trends in information management
Mega trends in information managementMega trends in information management
Mega trends in information management
 
Big datacamp2013 share
Big datacamp2013 shareBig datacamp2013 share
Big datacamp2013 share
 
Hadoop, Oracle and the big data revolution collaborate 2013
Hadoop, Oracle and the big data revolution collaborate 2013Hadoop, Oracle and the big data revolution collaborate 2013
Hadoop, Oracle and the big data revolution collaborate 2013
 
Hadoop, oracle and the industrial revolution of data
Hadoop, oracle and the industrial revolution of data Hadoop, oracle and the industrial revolution of data
Hadoop, oracle and the industrial revolution of data
 
Making the most of ssd in oracle11g
Making the most of ssd in oracle11gMaking the most of ssd in oracle11g
Making the most of ssd in oracle11g
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Hadoop and rdbms with sqoop
Hadoop and rdbms with sqoop Hadoop and rdbms with sqoop
Hadoop and rdbms with sqoop
 
Next generation databases july2010
Next generation databases july2010Next generation databases july2010
Next generation databases july2010
 
Optimize oracle on VMware (April 2011)
Optimize oracle on VMware (April 2011)Optimize oracle on VMware (April 2011)
Optimize oracle on VMware (April 2011)
 
Optimizing Oracle databases with SSD - April 2014
Optimizing Oracle databases with SSD - April 2014Optimizing Oracle databases with SSD - April 2014
Optimizing Oracle databases with SSD - April 2014
 
Understanding Solid State Disk and the Oracle Database Flash Cache (older ver...
Understanding Solid State Disk and the Oracle Database Flash Cache (older ver...Understanding Solid State Disk and the Oracle Database Flash Cache (older ver...
Understanding Solid State Disk and the Oracle Database Flash Cache (older ver...
 
Performance By Design
Performance By DesignPerformance By Design
Performance By Design
 
Optimize Oracle On VMware (Sep 2011)
Optimize Oracle On VMware (Sep 2011)Optimize Oracle On VMware (Sep 2011)
Optimize Oracle On VMware (Sep 2011)
 
Thanks for the Memory
Thanks for the MemoryThanks for the Memory
Thanks for the Memory
 
Top 10 tips for Oracle performance
Top 10 tips for Oracle performanceTop 10 tips for Oracle performance
Top 10 tips for Oracle performance
 
How I learned to stop worrying and love Oracle
How I learned to stop worrying and love OracleHow I learned to stop worrying and love Oracle
How I learned to stop worrying and love Oracle
 
Performance By Design
Performance By DesignPerformance By Design
Performance By Design
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

High Performance Plsql

Hinweis der Redaktion

  1. I’m worried about the Toad in the red shirt – we all know that red-shirt crewmen die in Star Trek!
  2. This presentation contains a wide variety of PL/SQL performance best practicesand tuning techniques, but we shouldn’t just pick one of these at random! Instead,our first step should be to identify the most resource-intensive lines ofPL/SQL code and start by optimizing that code.To do this, we use the PL/SQL profiler. The profiler is implemented in thepackage DBMS_PROFILER. When we surround a program call with START_PROFILER and STOP_PROFILER calls, Oracle collates execution statistics on aline-by-line basis.
  3. The profiling data is stored in a collection of tables prefixed withPLSQL_PROFILER. The above is a query that reports the most expensivelines of code (in terms of execution time) in the profiling run
  4. Much of the time identifying the most-expensive lines of code is sufficient to discoverhot spots and tuning opportunities. But on other occasions you need toidentify expensive subroutines, or identify the calling routine to understand the context in which a line of code is being executed. To help with these scenarios,Oracle introduced the hierarchical profiler in Oracle 11g.You access this profiler via the DBMS_HPROF package. START_PROFILING and STOP PROFILING procedures commence and terminate the profilingrun. The output from the profiling session will be written to the external file identifiedin the START_PROFILING call. If you want to load this file into database tablesfor analyses, you can do so by using the ANALYZE procedure.In this example, we profile the NIGHTLY_BATCH procedure to an externalfile hprof_trace.trc that is created in the HPROF_DIR directory. We then load thetrace file into the profiling tables using the ANALYZE procedure
  5. There are two ways to analyze the trace file. First, the plshprof commandline utility converts the trace file into an html report. We can view the report by pointing our browser at the hprof_report.htmlfile generated by the preceding command. The figure above shows the report.
  6. Personally, I find the HTML report a bit hard to interpret and prefer to issueSQL against the profiler tables. In the above example, a hierarchical self-join isissued that exposes the call tree
  7. Consider a scenario in which an application accepts input from the enduser, reads some data in the database, decides what statement to execute next, retrievesa result, makes a decision, executes some SQL, and so on. If the applicationcode is written entirely outside of the database, each of these steps would requirea network round trip between the database and the application. The timetaken to perform these network trips can easily dominate overall user responsetime.The right hand diagram shows the sequences of interactions that would be required withouta stored procedure approach.On the other hand, if a stored program is used to implement the fundstransfer logic, only a single database interaction is required. The stored programtakes responsibility for checking balances, withdrawal limits, and soon. The figure on the left illustrates stored procedure network traffic.
  8. Network round trips can also become significant when an application is requiredto perform some kind of aggregate processing on large record sets in thedatabase. If the application needs to (for example) retrieve millions of rows to calculatesome sort of business metric that cannot easily be computed using nativeSQL (average time to complete an order, for example), a large number of roundtrips can result. In such a case, the network delay can again become the dominantfactor in application response time. Performing the calculations in a stored programwill reduce network overhead, which might reduce overall response time.The key determining factor will be the network latency
  9. The further the code is (in network terms) from the database, the more the network effects will magnify. You can’t get any closer to the database than being inde the database as PL/SQL
  10. For the majority of PL/SQL programs, the biggest gains will be obtained by tuning the SQL within the PL/SQL.Next most important is usually to ensure that PL/SQL handles data efficiently: by using array fetch and insert, by using the right types of collections and best practices such as associative array lookups and NOCOPY parameters. Thirdly one should look at the algorithmic efficiency of the PL/SQL code: loop structure, ordering of conditionals, avoiding recursion and so on.Usually the least gain is obtained by tweaking parameters or data types. Two exception are:If PLSQL_OPTIMIZE_LEVEL is <2 (10g) or 3 (11g) then increasing it can sometimes lead to significant improvementsWhen doing number crunching, data types and native compilation are recommended
  11. Most parameters have little effect, but PLSQL_OPTIMIZE_LEVEL has major effect on PLSQL code, similar to the effects of an optimizing compiler in other languages. Level 0: No optimizationLevel 1: Minor optimizations, not much reorganizationLevel 2: (the default) Significant reorganization including loop optimizations and automatic bulk collectLevel 3: (11g only) Further optimizations, notably automatic in-lining of subroutines
  12. This script shows the amount of times routines spent in PL/SQL code compared to total execution timeThe procedure shown spends only 3% of it’s time executing PL/SQL code: the vast bulk of time is spent by SQL embedded within the PL/SQL.
  13. If you are a TOAD or SQL*Navigator user, consider the Xpert editions or the Development suites. These include SQL optimizer which can help you find and tune SQL
  14. PL/SQL can fetch rows from the database one at a time, all at once or in batches. The more rows fetched in a batch, the lower the CPU / logical read overhead, but the greater the memory requirementsThe forth way is not to retrieve it at all. I.e. Can you do all you work in SQL without pulling the rows into PL/SQL?
  15. Prior to 10g this is inefficient:*Excessive loop iterations Increases logical reads (rows in the same block fetched separately)In other languages, this pattern causes excessive network traffic, but luckily in PL/SQL this is not an issue.
  16. Selects all data in a single operationLarge result sets might take longer as memory growsOther concurrent sessions may have limited memory for sorts, etc. Out of memory errors are possibleIf you are connected via MTS and have Auto Shared Memory Management (ASMM) or Automatic Memory Management (AMM) you can actually use up all of the PGA and SGA memory.
  17. Considered best:Never more that p_array_size elements in collectionBest throughput, acceptable memory utilization
  18. See http://guyharrison.squarespace.com/blog/2009/9/18/mts-amm-bulk-collect-trouble.html
  19. Note that this example is also vulnerable to SQL injection. Bind variables enable SQLs that are essentially identical, differing onlyin parameter values, to be parsed only once and then executed many times. Usingbind variables reduces parse overhead—a CPU-intensive operation—and also reducescontention for latches and mutexes that protect shared SQL structures inthe shared pool.In most programming languages, we have to go to special effort to use bindvariables, and sometimes the convoluted code that results can be tedious to writeand hard to maintain. However in PL/SQL, bind variables are employed automatically:Every PL/SQL variable inside a SQL statement is effectively a bindvariable and, therefore, PL/SQL programs rarely suffer from parse overhead andassociated latch/mutex contention issues that are all too common in languagessuch as PHP, Java, or C#.However, when we use dynamic SQL in PL/SQL, this automatic bindingdoes not occur: Dynamically constructed SQL in PL/SQL is just
  20. This implementation defines the bind variable placeholder as :columnValuein the dynamic SQL string. The actual value is provided by the USING clause.Although we still request the parse every time this routine is executed, Oraclewill quite possibly find a matching SQL in the shared pool, providing onlythat the same table and column names have been used in a previous execution.
  21. As well as this performance gain, we reduce the chance of mutex contention if there are other sessions are trying to execute similar routines.
  22. Users of other programming languages might be familiar with the concept ofpassing a parameter by value as opposed to by reference. When we pass a parameterby value, we create a copy of the parameter for the subroutine to use. Whenwe pass the parameter by reference, the subroutine uses the actual variablepassed; any changes made to the variable in the subroutine are visible to the callingroutine.The NOCOPY directive instructs PL/SQL function or procedure to use theparameter variable directly, by reference, rather than making a copy. This is animportant optimization when passing large PL/SQL collections into a subroutinebecause otherwise the process of creating a copy can consume significant resources.
  23. Prior to Oracle 9.2, when seeking a non-numeric value in such a cache, we might use two collections: oneof which contained keys and the other which contained values. For instance, inthe following example, we scan through the G_CUST_NAMES table looking for aspecific customer name and date of birth. birth. If we find a match, we look in the correspondingindex of the G_CUST_IDS table to find the CUSTOMER_ID.
  24. Associative arrays offer a more efficient solution. An associativearray might be indexed by a non-numeric variable; so we can look up thematching customer name directly. And the code is simpler.
  25. The LOOP–END LOOP clauses repeatedly execute statements within a loop. Becausestatements within a loop are executed many times, they can often consumea high proportion of overall execution time. A badly constructed loop can have adrastic effect on performance.The code above illustrates the principle of exiting a loop as early as possible.The code calculates the number of prime numbers less than the numberprovided as a parameter (P_NUM). It does this by attempting to divide the numberby every number smaller than the parameter.I originally wrote this code many years ago when comparing Java andPL/SQL performance. In the first version of this code, I omitted to include theEXIT statement included as a comment in line 16. The program worked but performedpoorly because it kept looping when it did not need to. NB: PLSQL_OPTIMIZE_LEVEL cannot help here.
  26. Loop invariant expressions are those that don’t change with each iteration ofthe loop. For instance in the following code, the expressions on lines 5 and 7 remainunchanged with each iteration of the loop that begins on line 3. Recalculatingthese expressions with each iteration of the loop is unnecessary and wastesCPU cycles.
  27. A recursive routine is one that invokes itself. Recursive routines often offer elegantsolutions to complex programming problems but tend to consume large amountsof memory and to be less efficient than iterative—loop based—alternatives.
  28. Remember, the memory youscomes from a pool of memory shared between sessions. Other sessions might have reduced access to memory.
  29. So far, we have used the Oracle NUMBER data type when performing numericcomputation. The NUMBER type is extremely flexible and capable of storing bothhigh-precision and high-magnitude numbers. However, this flexibility comes at acost when performing numeric computations: Certain numeric calculations willbe faster if a less flexible data type is chosen.In particular, the PLS_INTEGER and SIMPLE_INTEGER data types performfaster than the NUMBER type for computation. Both are signed 32 bit integers,which means that they can store numbers between –2,147,483,648 and2,147,483,648. SIMPLE_INTEGER is the same as PLS_INTEGER but cannot beNULL and overflows (attempts to store numbers larger than 2,147,483,648, for instance)will not cause exceptions to be raised. SIMPLE_INTEGER can offer a performanceadvantage when the PL/SQL package is compiled to native code.
  30. Oracle enables you to create stored procedures in the Java language. Java-storedprocedures can outperform PL/SQL for number crunching, though the advantagesof Java for computation have been steadily decreasing with each release of Oracle.When Java was first introduced, performance gains of anywhere between 10 to 100times were achievable when rewriting computationally intensive PL/SQL routinesin Java. However, improvements in PL/SQL language efficiency, including someof the optimizations outlined in this chapter, have closed the gap.As with all computational optimizations, using Java to optimize numbercrunching operations is not generally advisable for PL/SQL programs that aredatabase-intensive. Efforts to optimize math operations for a PL/SQL programthat does mainly database operations are probably misdirected.Furthermore, a lot of the advantages that Java had over PL/SQL in previousreleases can be overcome in Oracle 11g by using efficient data types, SIMPLE_INTEGER, for example, and native compilation.
  31. This example illustrates a drawback of function caching. The query is not strictly deterministic, and should be flushed on a daily basis. Oracle 11g introduced the result set cache, which allows entire result sets to becached in memory. SQL statements that perform expensive operations on relativelystatic tables can benefit tremendously from the result set cache.The function cache is a related facility that can benefit PL/SQL routines orSQL statements that call PL/SQL functions. Oracle 11g can store the results of a PL/SQL function in memory and, if the function is expensive to resolve, can retrievethe results for the function from memory more efficiently than by reexecutingthe function.You might want to use the function cache in the following circumstances:❏ You have a computationally expensive function that is deterministic: It willalways return the same results given the same inputs.❏ You have a database access routine encapsulated in a function that accessestables that are infrequently updated.
  32. Einstein’s famous equation is encapsulated in the MASS_TO_ENERGY subroutinein lines 1–9; this subroutine is called multiple times from within the EMC2Bprocedure at line 17. This encapsulation represents good programming practice,especially if Einstein’s equation needs to be called from other routines. (Perhaps thispackage will be utilized in Larry Ellison’s upcoming intergalactic yacht.) However,the subroutine calls add overhead, and from a performance point of view, it wouldprobably be better to include the equation directly within the calling routine, like this:
  33. With 11g in-lining, you can write your code using modularity and encapsulationwithout paying a performance penalty because Oracle can automatically moverelevant subroutines in-line to improve performance. The optimizer will performsome in-lining automatically if PLSQL_OPTIMZE_LEVEL=3. If you want to performin-lining when PLSQL_OPTIMIZE_LEVEL=2 (the default in Oracle 11g) oryou want to increase the likelihood of in-lining when PLSQL_OPTIMIZE_LEVEL=3.
  34. Some of these and other topics are covered in Chapter 12 of my book “Oracle Performance Survival Guide”.