Deze presentatie is gegeven tijdens de KScope conferentie 2012
Spreker: Patrick Barel
Titel Can Collections Speed Up Your PL/SQL?
Onderwerp: Developers Toolbox - Coding
Deze presentatie gaat over het gebruik van Collections in PL/SQL. Hoe werken deze arrays? Hoe gebruikt Oracle deze structuren in één van de belangrijkste verbeteringen op het gebied van prestaties van PL/SQL code in combinatie met uitgevoerde SQL queries? Daarnaast wordt er ingegaan op het gebruik van Table Functions, waarmee je kracht van PL/SQL in SQL kunt gebruiken. In deze sessie leer je om met minimale inspanning een grote verbetering in de performance en onderhoudbaarheid van je PL/SQL code te bereiken.
This document provides a cheat sheet for PostgreSQL, listing useful commands for logging in, querying databases and tables, managing users and roles, monitoring performance, and more. It also includes examples of common queries for listing objects, casting data types, and analyzing query plans.
The document discusses C structures and provides examples. Some key points:
- Structures allow grouping of different data types under a single name. This is useful for representing records like books with attributes like title, author, etc.
- To define a structure, the struct statement is used along with member definitions of different data types. Structure variables can then be declared.
- Structures can be accessed using dot (.) or arrow (->) operators with structure variables or pointers. Arrays of structures allow storing multiple records.
- Structures can be passed to functions by value or by reference. Global structure variables are visible to all functions without needing to pass.
- Structure memory allocation packs elements contiguously
• For a full set of 350+ questions. Go to
• https://skillcertpro.com/product/microsoft-sc-900-exam-questions/
• SkillCertPro offers detailed explanations to each question which helps to understand the concepts better.
• It is recommended to score above 85% in SkillCertPro exams before attempting a real exam.
• SkillCertPro updates exam questions every 2 weeks.
• You will get life time access and life time free updates
• SkillCertPro assures 100% pass guarantee in first attempt.
Este documento resume o período do Império Brasileiro sob o II Reinado de 1840 a 1889. O texto descreve a política interna e externa do período, destacando as disputas entre liberais e conservadores e as guerras contra países vizinhos. Também apresenta os principais aspectos da economia brasileira da época, com foco na expansão da cultura do café.
El documento describe las estructuras y uniones en C. Las estructuras permiten agrupar múltiples tipos de datos bajo un solo nombre, mientras que las uniones almacenan múltiples campos en la misma posición de memoria. El documento explica cómo declarar, definir variables, acceder e inicializar estructuras, así como el uso de estructuras anidadas, arrays de estructuras y estructuras como parámetros. También cubre uniones, enumeraciones y campos de bits.
Este documento describe las estructuras de datos de pilas y colas. Explica que las pilas siguen el principio LIFO (último en entrar, primero en salir) y las colas siguen el principio FIFO (primero en entrar, primero en salir). También presenta implementaciones de pilas y colas estáticas en Java y C usando vectores, y menciona que las estructuras dinámicas usan listas enlazadas.
El método de hash por medio al cuadrado consiste en elevar la clave al cuadrado y tomar los dígitos centrales como la dirección de almacenamiento. La función hash se define como los dígitos centrales de la clave elevada al cuadrado más uno. Es importante extraer los mismos dígitos de la misma posición para cada clave debido al tamaño del archivo.
This document provides a cheat sheet for PostgreSQL, listing useful commands for logging in, querying databases and tables, managing users and roles, monitoring performance, and more. It also includes examples of common queries for listing objects, casting data types, and analyzing query plans.
The document discusses C structures and provides examples. Some key points:
- Structures allow grouping of different data types under a single name. This is useful for representing records like books with attributes like title, author, etc.
- To define a structure, the struct statement is used along with member definitions of different data types. Structure variables can then be declared.
- Structures can be accessed using dot (.) or arrow (->) operators with structure variables or pointers. Arrays of structures allow storing multiple records.
- Structures can be passed to functions by value or by reference. Global structure variables are visible to all functions without needing to pass.
- Structure memory allocation packs elements contiguously
• For a full set of 350+ questions. Go to
• https://skillcertpro.com/product/microsoft-sc-900-exam-questions/
• SkillCertPro offers detailed explanations to each question which helps to understand the concepts better.
• It is recommended to score above 85% in SkillCertPro exams before attempting a real exam.
• SkillCertPro updates exam questions every 2 weeks.
• You will get life time access and life time free updates
• SkillCertPro assures 100% pass guarantee in first attempt.
Este documento resume o período do Império Brasileiro sob o II Reinado de 1840 a 1889. O texto descreve a política interna e externa do período, destacando as disputas entre liberais e conservadores e as guerras contra países vizinhos. Também apresenta os principais aspectos da economia brasileira da época, com foco na expansão da cultura do café.
El documento describe las estructuras y uniones en C. Las estructuras permiten agrupar múltiples tipos de datos bajo un solo nombre, mientras que las uniones almacenan múltiples campos en la misma posición de memoria. El documento explica cómo declarar, definir variables, acceder e inicializar estructuras, así como el uso de estructuras anidadas, arrays de estructuras y estructuras como parámetros. También cubre uniones, enumeraciones y campos de bits.
Este documento describe las estructuras de datos de pilas y colas. Explica que las pilas siguen el principio LIFO (último en entrar, primero en salir) y las colas siguen el principio FIFO (primero en entrar, primero en salir). También presenta implementaciones de pilas y colas estáticas en Java y C usando vectores, y menciona que las estructuras dinámicas usan listas enlazadas.
El método de hash por medio al cuadrado consiste en elevar la clave al cuadrado y tomar los dígitos centrales como la dirección de almacenamiento. La función hash se define como los dígitos centrales de la clave elevada al cuadrado más uno. Es importante extraer los mismos dígitos de la misma posición para cada clave debido al tamaño del archivo.
1. O Golpe da Maioridade antecipou a maioridade de D. Pedro II aos 15 anos para que assumisse o trono, encerrando um período de instabilidade política no Brasil.
2. Para resolver os conflitos entre liberais e conservadores, D. Pedro II implantou o parlamentarismo no Brasil, no qual ministros eram nomeados conforme a maioria no parlamento.
3. A Guerra do Paraguai (1864-1870) opôs a Tríplice Aliança formada pelo Brasil, Argentina e Uruguai contra o Paraguai,
O documento discute as principais ideologias do século XIX, incluindo o socialismo utópico, o socialismo científico de Marx e Engels, e o anarquismo. O socialismo utópico propunha uma sociedade igualitária sem propriedade privada de forma gradual, enquanto Marx pregava a revolução do proletariado. Os anarquistas rejeitavam o Estado e defendiam a cooperação social e autogestão.
Data Visualization Techniques in Power BIAngel Abundez
A progression from fundamental charts to more advanced ways to look at data. We end with Custom Visuals and R Visuals that extend this visualization platform.
Lec8 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Dynamic Sch...Hsien-Hsin Sean Lee, Ph.D.
The document discusses dynamic scheduling in modern out-of-order processors. It describes how register renaming is used to avoid false dependencies and allow instructions to execute out-of-order. The reorder buffer (ROB) is used to support precise interrupts by buffering instruction results and allowing the processor state to be reconstructed sequentially. The ROB also handles precise handling of speculative execution for branch mispredictions.
Presentación del Canal de Isabel Segunda en el Seminario Esri sobre soluciones tecnológicas para la gestión del abastecimiento y saneamiento del agua, celebrado el pasado 21 de marzo en Madrid.
Si quieres más información visita nuestra web: esri.es o contacta con nosotros en informacion@esri.es
This document provides an overview of context switching in PL/SQL and best practices for reducing context switches using bulk binding techniques like BULK COLLECT and FORALL. It discusses how context switching occurs between the PL/SQL and SQL engines and how to avoid SQL statements in loops. It then demonstrates the syntax for BULK COLLECT and FORALL and provides an example of their use to update multiple rows with one context switch. The document concludes with discussions on best practices like using LIMIT with BULK COLLECT and avoiding cursor attributes like %NOTFOUND.
As an APEX Developer you might have experienced that conventional CSS has its drawbacks. And you might have heard about LESS, SCSS, SASS and other weird acronyms. So what do these acronyms mean to you and why should you care?
In this session you will learn how to bring your CSS skill set to the next level using the opportunities brought to you by these new techniques. Although these skills can be applied to any web project, in this session we will be targeting APEX applications.
This document discusses troubleshooting APEX applications. It describes how to enable debugging and tracing in both develop and runtime modes. It also covers logging APEX activity and examining logs to diagnose performance issues. The example problem discussed was an application making excessive calls to retrieve images from the database, slowing it down. The solution was to move the images to a web server to leverage caching.
The document discusses the Oracle query optimizer. It describes the key components and steps of the optimizer including the query transformer, query estimator, and plan generator. The query transformer rewrites queries for better performance through techniques like view merging, predicate pushing, and subquery unnesting. The query estimator calculates selectivity, cardinality, and cost to determine the overall cost of execution plans. The plan generator explores access paths, join methods, and join orders to select the lowest cost plan.
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEXEnkitec
This document discusses handling file attachments in Oracle Application Express (APEX) applications. It covers using BLOBs, CLOBs, and LOBs to store file attachments in the database; the APEX BLOB wizard; configuring a custom table; and displaying attachments in forms and reports. Advanced topics covered include LOB storage options, sizing database objects, and using a rich text editor plugin to handle text attachments. The goal is to understand how to accept, store, and display different file types uploaded by users in an APEX application.
This document discusses automatic testing of APEX applications. It describes different types of tests including acceptance tests, integration tests, and unit tests. It advocates for automating these tests using tools like Selenium to reduce time to market, find defects early, and improve test coverage. Automating unit tests in PL/SQL, integration tests using APIs and components, and acceptance tests using criteria like performance and functionality are proposed. Testing APEX applications with Selenium is demonstrated.
The Amazing and Elegant PL/SQL Function Result CacheSteven Feuerstein
The Function Result Cache, introduced in Oracle Database 11g, offers a very elegant way to cache cross-session data and make it available via PL/SQL functions. It can have a dramatic performance impact on fetching static data (even static for just a period of time) - and it's managed automatically by Oracle Database for you!
This document provides coding best practices and guidelines for PL/SQL. It covers topics such as naming conventions, coding standards, variables and data types, control structures, exception handling, and formatting. The guidelines recommend using descriptive naming conventions, avoiding dead code and literals, using anchored declarations, handling exceptions properly, and consistently formatting code for readability. Adhering to these standards helps produce cleaner, more maintainable code.
The document introduces generic collection types that can enrich the PLSQL programmer's toolkit by providing commonly used data structures like lists, maps, sets, trees, and graphs. It describes the current status of available collection types and utility packages that extend their functionality. Practical examples are provided for using lists, simple maps, hash maps, and base maps to represent ordered collections, key-value pairs, and interconnected elements in graphs. Developers are encouraged to try out these generic collection types and provide feedback to further improve the tools.
Striving for Perfection: The Ultimate APEX Application ArchitectureRoel Hartman
APEX supports a flexible architecture. That means that there are multiple ways of solving problems like: separation of data and logic, security issues, re-use, including javascript and CSS, etc. etc.
In this session I'll give the pro's and cons of each available option. As this is aimed to be an interactive session, the attendees are encouraged to put forward their own ideas - and concerns. So, maybe, in the end, we'll reach the "Ultimate APEX Application Architecture"!
Oracle Text is a facility within the database that provides more advanced indexing & search techniques - including the ability to index documents stored in your database; on your server; or even the web!
Now you can incorporate this functionality into your web application using Oracle Application Express.
This presentation will demonstrate how easy it is to combine the two, and give you a platform for further expansion and exploration within a very powerful product.
Introduction to PL/SQL exceptions
Oracle error codes
Pragmas
User Defined Exception and Pragma EXCEPTION_INIT
DBMS_UTILITY package
Guidelines for exception handling
Guidelines for exception handling - FORALL
Foolproof your PL/SQL programs – Standalone procs and functions
Foolproof your PL/SQL programs - packages
Foolproof your PL/SQL programs - Assumptions
Foolproof your PL/SQL programs - Tracing
This document discusses techniques for improving SQL query performance by avoiding function calls in SQL queries and leveraging caching mechanisms. It covers scalar subquery caching, which caches the results of functions used in scalar subqueries to avoid repeated execution. Deterministic functions are also discussed, which Oracle can optimize by caching results. The document then introduces the cross-session PL/SQL function result cache and SQL result cache available in Oracle 11g, which cache and reuse function results and full query results across sessions to improve response times for repetitive queries and functions.
utPLSQL offers a unit testing API for PL/SQL that is modeled on the xUnit approach. This is an old slide deck on utPLSQL so my apologies for any inconsistencies with the current utility. Note: while I created the original utPLSQL code base, I am not actively working on utPLSQL at this time. Check out github.com/utplsql for the code and project details.
Over the years there have been countless technical and social presentations doting on 5, 10, 12 ways to improve this, that and the other.
I will go through various performance tweaks (not tweets) for Oracle Application Express without limiting myself to a golden number.
These improvements will vary from simple PL/SQL refactoring; to monitoring for bottlenecks in your application; to cutting down maintenance time - which relates to the performance of you as an Oracle developer with only 24 hours in a day.
We may even visit a little APEX instrumentation on the way.
The document provides guidelines for optimizing SQL and PL/SQL code for performance. It discusses best practices for using indexes like creating them on frequently queried columns and avoiding functions on indexed columns. Other topics covered include using EXISTS instead of JOINs when possible, avoiding DISTINCT, and placing filters in the WHERE clause instead of HAVING. Modular code design, avoiding negatives and LIKE patterns, and letting the optimizer do its work are also recommended. The goal is to help programmers write efficient code by understanding query execution and tuning techniques.
1. O Golpe da Maioridade antecipou a maioridade de D. Pedro II aos 15 anos para que assumisse o trono, encerrando um período de instabilidade política no Brasil.
2. Para resolver os conflitos entre liberais e conservadores, D. Pedro II implantou o parlamentarismo no Brasil, no qual ministros eram nomeados conforme a maioria no parlamento.
3. A Guerra do Paraguai (1864-1870) opôs a Tríplice Aliança formada pelo Brasil, Argentina e Uruguai contra o Paraguai,
O documento discute as principais ideologias do século XIX, incluindo o socialismo utópico, o socialismo científico de Marx e Engels, e o anarquismo. O socialismo utópico propunha uma sociedade igualitária sem propriedade privada de forma gradual, enquanto Marx pregava a revolução do proletariado. Os anarquistas rejeitavam o Estado e defendiam a cooperação social e autogestão.
Data Visualization Techniques in Power BIAngel Abundez
A progression from fundamental charts to more advanced ways to look at data. We end with Custom Visuals and R Visuals that extend this visualization platform.
Lec8 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Dynamic Sch...Hsien-Hsin Sean Lee, Ph.D.
The document discusses dynamic scheduling in modern out-of-order processors. It describes how register renaming is used to avoid false dependencies and allow instructions to execute out-of-order. The reorder buffer (ROB) is used to support precise interrupts by buffering instruction results and allowing the processor state to be reconstructed sequentially. The ROB also handles precise handling of speculative execution for branch mispredictions.
Presentación del Canal de Isabel Segunda en el Seminario Esri sobre soluciones tecnológicas para la gestión del abastecimiento y saneamiento del agua, celebrado el pasado 21 de marzo en Madrid.
Si quieres más información visita nuestra web: esri.es o contacta con nosotros en informacion@esri.es
This document provides an overview of context switching in PL/SQL and best practices for reducing context switches using bulk binding techniques like BULK COLLECT and FORALL. It discusses how context switching occurs between the PL/SQL and SQL engines and how to avoid SQL statements in loops. It then demonstrates the syntax for BULK COLLECT and FORALL and provides an example of their use to update multiple rows with one context switch. The document concludes with discussions on best practices like using LIMIT with BULK COLLECT and avoiding cursor attributes like %NOTFOUND.
As an APEX Developer you might have experienced that conventional CSS has its drawbacks. And you might have heard about LESS, SCSS, SASS and other weird acronyms. So what do these acronyms mean to you and why should you care?
In this session you will learn how to bring your CSS skill set to the next level using the opportunities brought to you by these new techniques. Although these skills can be applied to any web project, in this session we will be targeting APEX applications.
This document discusses troubleshooting APEX applications. It describes how to enable debugging and tracing in both develop and runtime modes. It also covers logging APEX activity and examining logs to diagnose performance issues. The example problem discussed was an application making excessive calls to retrieve images from the database, slowing it down. The solution was to move the images to a web server to leverage caching.
The document discusses the Oracle query optimizer. It describes the key components and steps of the optimizer including the query transformer, query estimator, and plan generator. The query transformer rewrites queries for better performance through techniques like view merging, predicate pushing, and subquery unnesting. The query estimator calculates selectivity, cardinality, and cost to determine the overall cost of execution plans. The plan generator explores access paths, join methods, and join orders to select the lowest cost plan.
LOBS, BLOBS, CLOBS: Dealing with Attachments in APEXEnkitec
This document discusses handling file attachments in Oracle Application Express (APEX) applications. It covers using BLOBs, CLOBs, and LOBs to store file attachments in the database; the APEX BLOB wizard; configuring a custom table; and displaying attachments in forms and reports. Advanced topics covered include LOB storage options, sizing database objects, and using a rich text editor plugin to handle text attachments. The goal is to understand how to accept, store, and display different file types uploaded by users in an APEX application.
This document discusses automatic testing of APEX applications. It describes different types of tests including acceptance tests, integration tests, and unit tests. It advocates for automating these tests using tools like Selenium to reduce time to market, find defects early, and improve test coverage. Automating unit tests in PL/SQL, integration tests using APIs and components, and acceptance tests using criteria like performance and functionality are proposed. Testing APEX applications with Selenium is demonstrated.
The Amazing and Elegant PL/SQL Function Result CacheSteven Feuerstein
The Function Result Cache, introduced in Oracle Database 11g, offers a very elegant way to cache cross-session data and make it available via PL/SQL functions. It can have a dramatic performance impact on fetching static data (even static for just a period of time) - and it's managed automatically by Oracle Database for you!
This document provides coding best practices and guidelines for PL/SQL. It covers topics such as naming conventions, coding standards, variables and data types, control structures, exception handling, and formatting. The guidelines recommend using descriptive naming conventions, avoiding dead code and literals, using anchored declarations, handling exceptions properly, and consistently formatting code for readability. Adhering to these standards helps produce cleaner, more maintainable code.
The document introduces generic collection types that can enrich the PLSQL programmer's toolkit by providing commonly used data structures like lists, maps, sets, trees, and graphs. It describes the current status of available collection types and utility packages that extend their functionality. Practical examples are provided for using lists, simple maps, hash maps, and base maps to represent ordered collections, key-value pairs, and interconnected elements in graphs. Developers are encouraged to try out these generic collection types and provide feedback to further improve the tools.
Striving for Perfection: The Ultimate APEX Application ArchitectureRoel Hartman
APEX supports a flexible architecture. That means that there are multiple ways of solving problems like: separation of data and logic, security issues, re-use, including javascript and CSS, etc. etc.
In this session I'll give the pro's and cons of each available option. As this is aimed to be an interactive session, the attendees are encouraged to put forward their own ideas - and concerns. So, maybe, in the end, we'll reach the "Ultimate APEX Application Architecture"!
Oracle Text is a facility within the database that provides more advanced indexing & search techniques - including the ability to index documents stored in your database; on your server; or even the web!
Now you can incorporate this functionality into your web application using Oracle Application Express.
This presentation will demonstrate how easy it is to combine the two, and give you a platform for further expansion and exploration within a very powerful product.
Introduction to PL/SQL exceptions
Oracle error codes
Pragmas
User Defined Exception and Pragma EXCEPTION_INIT
DBMS_UTILITY package
Guidelines for exception handling
Guidelines for exception handling - FORALL
Foolproof your PL/SQL programs – Standalone procs and functions
Foolproof your PL/SQL programs - packages
Foolproof your PL/SQL programs - Assumptions
Foolproof your PL/SQL programs - Tracing
This document discusses techniques for improving SQL query performance by avoiding function calls in SQL queries and leveraging caching mechanisms. It covers scalar subquery caching, which caches the results of functions used in scalar subqueries to avoid repeated execution. Deterministic functions are also discussed, which Oracle can optimize by caching results. The document then introduces the cross-session PL/SQL function result cache and SQL result cache available in Oracle 11g, which cache and reuse function results and full query results across sessions to improve response times for repetitive queries and functions.
utPLSQL offers a unit testing API for PL/SQL that is modeled on the xUnit approach. This is an old slide deck on utPLSQL so my apologies for any inconsistencies with the current utility. Note: while I created the original utPLSQL code base, I am not actively working on utPLSQL at this time. Check out github.com/utplsql for the code and project details.
Over the years there have been countless technical and social presentations doting on 5, 10, 12 ways to improve this, that and the other.
I will go through various performance tweaks (not tweets) for Oracle Application Express without limiting myself to a golden number.
These improvements will vary from simple PL/SQL refactoring; to monitoring for bottlenecks in your application; to cutting down maintenance time - which relates to the performance of you as an Oracle developer with only 24 hours in a day.
We may even visit a little APEX instrumentation on the way.
The document provides guidelines for optimizing SQL and PL/SQL code for performance. It discusses best practices for using indexes like creating them on frequently queried columns and avoiding functions on indexed columns. Other topics covered include using EXISTS instead of JOINs when possible, avoiding DISTINCT, and placing filters in the WHERE clause instead of HAVING. Modular code design, avoiding negatives and LIKE patterns, and letting the optimizer do its work are also recommended. The goal is to help programmers write efficient code by understanding query execution and tuning techniques.
Abstract: Developers - If you are not using Bulk Binds you are not writing PL/SQL efficiently!
Bulk binding has been around for a long time, yet there are sites out there that don't utilise this feature to its full extent, if at all. Every release of Oracle improves on this functionality so obviously it's a topic worthy of consistent awareness.
In PL/SQL and SQL, there are a few nifty features related to bulk binding you may not have seen - it's not all about BULK COLLECT. Whether you're on 8i, 11g or anything in between, you'll benefit from the concepts described in this seminar and become a Bulk Binding Baron!
Oracle Application Express (APEX) is shipped with several JavaScript libraries, jQuery being the best known one of them. And on top of these libraries the APEX Development Team created their own. You probably used a couple of these API's already, like $s, $v etc.
But there are way more and some of them are extremely useful. But first you have to be aware they exists. And secondly you have to know how to use the properly.
This session will cover the most valuable JavaScript API's with some real world examples.
Most developers stick to the standard $s and $v functions - even without knowing there is also a $v2 and $s can have more parameters.
The focus will be on the namespaced apex API's, like apex.server.process and apex.event.trigger.
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingSteven Feuerstein
Is your Oracle Database application running slower than you'd like? One of the first things to check is row-by-row processing: non-query DML (insert, update, delete) within a loop. And the fix? Bulk processing, either with smarter SQL or with FORALL and BULK COLLECT in PL/SQL.
PL/Scope is a compiler tool that gathers information about identifiers (as of 11.1) and SQL statements (as of 12.2) in your PL/SQL code. You can do all sorts of amazing deep-dive analysis of your code with PL/Scope, answering questions like: Where is a variable assigned a value in a program? What variables are declared inside a given program? Which programs call another program (that is, you can get down to a subprogram in a package)? Find the type of a variable from its declaration. Show where specific columns are referenced. Locate all SQL statements containing hints. Find all dynamic SQL usages – ideal for getting rid of SQL injection vulnerabilities. Show all locations in your code where you commit or rollback. In other words, powerful impact analysis, built right into PL/SQL!
An array is a collection of similar data types stored under a common name. Arrays can be one-dimensional, two-dimensional, or multi-dimensional. Elements in an array are stored in contiguous memory locations. Arrays allow multiple variables of the same type to be manipulated together using a single name. Common operations on arrays include sorting elements, performing matrix operations, and CPU scheduling.
The document discusses pointers and arrays in C programming. It explains that an array stores multiple elements of the same type in contiguous memory locations, while a pointer variable stores the address of another variable. The summary demonstrates how to declare and initialize arrays and pointers, access array elements using pointers, pass arrays to functions by reference using pointers, and how pointers and arrays are related but not synonymous concepts.
The document discusses arrays in C programming language. It defines arrays as fixed-sized sequenced collections of elements of the same data type that share a common name. One-dimensional arrays represent lists, while two-dimensional arrays represent tables with rows and columns. Arrays must be declared before use with the size specified. Elements can be accessed using indices and initialized. Common operations like input, output, sorting and searching of array elements are demonstrated through examples.
Arrays can be passed to functions by reference, so any changes made to the array elements inside the function are reflected back in the calling function; the array name itself represents the base address of the array, which is passed to the function, while the size must be passed explicitly as a parameter; this allows the function to loop through the array and perform operations on each element using the indexes.
This document discusses one-dimensional and two-dimensional arrays in C/C++. It explains that a one-dimensional array stores a list of values of the same type, accessed via an index. A two-dimensional array consists of rows and columns. When passing an array to a function, only the array name is passed, which is essentially call by reference, with the function able to access elements via indices.
An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is a one-dimensional array which is a list of variables of same data type. An array of one-dimensional arrays is called a two-dimensional array.
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
Homework Assignment – Array Technical Document
Write a technical document that describes the structure and use of arrays. The document should
be 3 to 5 pages and include an Introduction section, giving a brief synopsis of the document and
arrays, a Body section, describing arrays and giving an annotated example of their use as a
programming construct, and a conclusion to revisit important information about arrays described
in the Body of the document. Some suggested material to include:
Declaring arrays of various types
Array pointers
Printing and processing arrays
Sorting and searching arrays
Multidimensional arrays
Indexing arrays of various dimension
Array representation in memory by data type
Passing arrays as arguments
If you find any useful images on the Internet, you can use them as long as you cite the source in
end notes.
Solution
Array is a collection of variables of the same type that are referenced by a common name.
Specific elements or variables in the array are accessed by means of index into the array.
If taking about C, In C all arrays consist of contiguous memory locations. The lowest address
corresponds to the first element in the array while the largest address corresponds to the last
element in the array.
C supports both single and multi-dimensional arrays.
1) Single Dimension Arrays:-
Syntax:- type var_name[size];
where type is the type of each element in the array, var_name is any valid identifier, and size is
the number of elements in the array which has to be a constant value.
*Array always use zero as index to first element.
The valid indices for array above are 0 .. 4, i.e. 0 .. number of elements - 1
For Example :- To load an array with values 0 .. 99
int x[100] ;
int i ;
for ( i = 0; i < 100; i++ )
x[i] = i ;
To determine to size of an array at run time the sizeof operator is used. This returns the size in
bytes of its argument. The name of the array is given as the operand
size_of_array = sizeof ( array_name ) ;
2) Initialisg array:-
Arrays can be initialised at time of declaration in the following manner.
type array[ size ] = { value list };
For Example :-
int i[5] = {1, 2, 3, 4, 5 } ;
i[0] = 1, i[1] = 2, etc.
The size specification in the declaration may be omitted which causes the compiler to count the
number of elements in the value list and allocate appropriate storage.
For Example :- int i[ ] = { 1, 2, 3, 4, 5 } ;
3) Multidimensional array:-
Multidimensional arrays of any dimension are possible in C but in practice only two or three
dimensional arrays are workable. The most common multidimensional array is a two
dimensional array for example the computer display, board games, a mathematical matrix etc.
Syntax :type name [ rows ] [ columns ] ;
For Example :- 2D array of dimension 2 X 3.
int d[ 2 ] [ 3 ] ;
A two dimensional array is actually an array of arrays, in the above case an array of two integer
arrays (the rows) each with three elements, and is stored row-wise in memory.
For Example :- Program to fill .
Arrays are ordered sets of elements of the same type that allow direct access to each element through an index. In C++, arrays have a fixed size that is declared, with elements accessed using square brackets and integers representing their position. Multidimensional arrays arrange data in tables and can be thought of as arrays of arrays. Elements are accessed using multiple indices separated by commas within the brackets.
The document discusses various aspects of arrays in C programming language. It defines arrays as collections of similar data types stored in contiguous memory locations. It describes single dimensional and multi-dimensional arrays. It also discusses array declaration and initialization syntax. Some key points covered are: advantages of arrays over single variables, accessing array elements using indexes, passing arrays to functions, and two dimensional or 2D arrays also called matrices.
A C program is provided to reorder a one-dimensional array of numbers in descending order. The program declares an integer array, prompts the user to enter the number of elements, reads the elements into the array, then uses nested for loops and a temporary variable to reorder the elements from highest to lowest value by swapping elements. The reordered array is then printed to display the output.
Here is a C program that multiplies two matrices using 2D arrays:
#include <stdio.h>
int main() {
int a[2][2], b[2][2], product[2][2], i, j, k;
printf("Enter elements of first matrix:\n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of second matrix:\n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf("%d", &
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
This is a presentation on Arrays, one of the most important topics on Data Structures and algorithms. Anyone who is new to DSA or wants to have a theoretical understanding of the same can refer to it :D
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
This document provides an overview of arrays and linked lists as data structures. It discusses arrays, including declaration, initialization, updating elements, and multi-dimensional arrays. It also covers searching arrays, why arrays are needed, pros and cons of arrays, and character strings as arrays. The document then introduces linked lists as a data structure and discusses linked list operations like printing all elements, adding nodes, appending nodes, inserting nodes, and deleting nodes. Homework questions on arrays and linked lists are provided at the end.
The document discusses different types of query languages used to retrieve data from a database. It states that there are two main types: procedural query languages and non-procedural query languages. Procedural query languages require the user to specify the step-by-step process to retrieve data, while non-procedural languages only require the user to specify what data to retrieve without how. Relational algebra is provided as an example of a procedural query language, while relational calculus is given as a non-procedural language. SQL is described as a practical implementation of both relational algebra and relational calculus used to interact with relational databases.
Arrays in C are collections of similar data types stored in contiguous memory locations that can be accessed via indexes, they can be declared with a specified data type and size and initialized with values, and multi-dimensional arrays allow the storage of two-dimensional data structures like matrices through multiple subscripts denoting rows and columns.
The objective of the Level 5 Diploma in Information Technology is to provide learners with an excellent foundation for a career in a range of organisations. It designed to ensure that each learner is ‘business ready’: a confident, independent thinker with a detailed knowledge of Information Technology, and equipped with the skills to adapt rapidly to change.
Similar to AMIS - Can collections speed up your PL/SQL? (20)
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio.
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio.
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio.
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio.
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio.
Ron Hendriks is an IoT consultant and enthusiast who provides his contact information. The document discusses industrial automation and IoT, including typical hardware architectures, automation levels, protocols, and processes. It also discusses standards like ISA 88 and ISA 95. Challenges for implementing IoT in industrial automation are listed, as well as recent developments and opportunities like introducing more IT and open communication protocols. The near future and potential applications of machine learning are also mentioned.
This document provides an introduction to machine learning, including: what machine learning is; why it is relevant; common algorithms and tools used; examples of use cases; and how to get started with machine learning. It discusses topics such as supervised vs. unsupervised learning, popular machine learning libraries and frameworks, deploying models, and resources for learning machine learning.
The document discusses Internet of Things (IoT) technology and its applications for asset monitoring. It provides an overview of an IoT solution for asset monitoring using devices such as beacons and LoRa sensors that communicate with an IoT cloud platform. The solution involves registering devices and publishing their real-time sensor data to the cloud, which can then be used for applications such as asset tracking dashboards, automated monitoring, and predictive maintenance. Contact information is provided for discussing customized IoT solutions.
The annual review session by the AMIS team on their findings, interpretations and opinions regarding news, trends, announcements and roadmaps around Oracle's product portfolio. This presentation discusses architecture trends, container technology, disruptive movements such as IoT, Blockchain, Intelligent Bots and Machine Learning, Modern User Experience, Enterprise Integration, Autonomous Systems in general and Autonomous Database in particular, Security, Cloud, Networking, Java, High PaaS & Low PaaS, DevOps, Microservices, Hybrid Cloud. This Oracle OpenWorld - more than any in recent history - rocked the foundations of the Oracle platform and opened up some real new roads ahead. This presentation leads you through the most relevant announcements and new directions.
Bridging the gap between Administrative and Operational IT
Vision, Architecure and Project experience. This slide deck shows our vision on this market for industrial enterprise IOT. Conclusion
The document discusses Oracle Management Cloud (OMC), a new management platform from Oracle designed to provide smarter insight and swifter action for IT organizations. It summarizes key challenges currently facing IT, such as being overwhelmed by operational data and lacking actionable insights. OMC aims to provide a complete, integrated suite of management solutions powered by machine learning to help customers manage heterogeneous applications and infrastructure across any cloud with greater agility and efficiency.
More from Getting value from IoT, Integration and Data Analytics (20)
The Department of Veteran Affairs (VA) invited Taylor Paschal, Knowledge & Information Management Consultant at Enterprise Knowledge, to speak at a Knowledge Management Lunch and Learn hosted on June 12, 2024. All Office of Administration staff were invited to attend and received professional development credit for participating in the voluntary event.
The objectives of the Lunch and Learn presentation were to:
- Review what KM ‘is’ and ‘isn’t’
- Understand the value of KM and the benefits of engaging
- Define and reflect on your “what’s in it for me?”
- Share actionable ways you can participate in Knowledge - - Capture & Transfer
"Choosing proper type of scaling", Olena SyrotaFwdays
Imagine an IoT processing system that is already quite mature and production-ready and for which client coverage is growing and scaling and performance aspects are life and death questions. The system has Redis, MongoDB, and stream processing based on ksqldb. In this talk, firstly, we will analyze scaling approaches and then select the proper ones for our system.
High performance Serverless Java on AWS- GoTo Amsterdam 2024Vadym Kazulkin
Java is for many years one of the most popular programming languages, but it used to have hard times in the Serverless community. Java is known for its high cold start times and high memory footprint, comparing to other programming languages like Node.js and Python. In this talk I'll look at the general best practices and techniques we can use to decrease memory consumption, cold start times for Java Serverless development on AWS including GraalVM (Native Image) and AWS own offering SnapStart based on Firecracker microVM snapshot and restore and CRaC (Coordinated Restore at Checkpoint) runtime hooks. I'll also provide a lot of benchmarking on Lambda functions trying out various deployment package sizes, Lambda memory settings, Java compilation options and HTTP (a)synchronous clients and measure their impact on cold and warm start times.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillLizaNolte
HERE IS YOUR WEBINAR CONTENT! 'Mastering Customer Journey Management with Dr. Graham Hill'. We hope you find the webinar recording both insightful and enjoyable.
In this webinar, we explored essential aspects of Customer Journey Management and personalization. Here’s a summary of the key insights and topics discussed:
Key Takeaways:
Understanding the Customer Journey: Dr. Hill emphasized the importance of mapping and understanding the complete customer journey to identify touchpoints and opportunities for improvement.
Personalization Strategies: We discussed how to leverage data and insights to create personalized experiences that resonate with customers.
Technology Integration: Insights were shared on how inQuba’s advanced technology can streamline customer interactions and drive operational efficiency.
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...Fwdays
Direct losses from downtime in 1 minute = $5-$10 thousand dollars. Reputation is priceless.
As part of the talk, we will consider the architectural strategies necessary for the development of highly loaded fintech solutions. We will focus on using queues and streaming to efficiently work and manage large amounts of data in real-time and to minimize latency.
We will focus special attention on the architectural patterns used in the design of the fintech system, microservices and event-driven architecture, which ensure scalability, fault tolerance, and consistency of the entire system.
Session 1 - Intro to Robotic Process Automation.pdfUiPathCommunity
👉 Check out our full 'Africa Series - Automation Student Developers (EN)' page to register for the full program:
https://bit.ly/Automation_Student_Kickstart
In this session, we shall introduce you to the world of automation, the UiPath Platform, and guide you on how to install and setup UiPath Studio on your Windows PC.
📕 Detailed agenda:
What is RPA? Benefits of RPA?
RPA Applications
The UiPath End-to-End Automation Platform
UiPath Studio CE Installation and Setup
💻 Extra training through UiPath Academy:
Introduction to Automation
UiPath Business Automation Platform
Explore automation development with UiPath Studio
👉 Register here for our upcoming Session 2 on June 20: Introduction to UiPath Studio Fundamentals: https://community.uipath.com/events/details/uipath-lagos-presents-session-2-introduction-to-uipath-studio-fundamentals/
Discover top-tier mobile app development services, offering innovative solutions for iOS and Android. Enhance your business with custom, user-friendly mobile applications.
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
AMIS - Can collections speed up your PL/SQL?
1. Developers Toolbox - Coding
Can collections speed up your PL/SQL?
Patrick Barel , AMIS, The Netherlands
Wednesday, June 27, 2012
ODTUG KScope 12
San Antonio, Texas, USA
5. Records
Record type definition
,
TYPE record_type IS RECORD ( field_definition ) ;
Field definition
NOT NULL
:=
expression
DEFAULT
field datatype
10. About Associative Arrays
Number of elements is unbounded, practically speaking.
Valid row numbers range from -231+1 to 231-1.
(i.e. -2,147,483,647 to 2,147,483,647)
This range allows you to employ the row number as an intelligent key,
such as the primary key or unique index value, because…
AAs also:
Can be sparse.
Data does not have to be stored in consecutive rows, as is required in
traditional 3GL arrays and VARRAYs.
Can have index values of integers or strings (Oracle9i R2
and above).
assoc_array_example.sql
collection_of_records.sql
count_vs_rowcount.sql
11. Associative Arrays
Name Changes:
7: PL/SQL Tables
8i: Index By Tables
9i: Associative Arrays
Single dimensioned, unbounded, sparse collection of
homogeneous elements
PL/SQL Only
key value
13. Associative Array
declare
type num_tbl is table of number
index by binary_integer;
l_num_tbl num_tbl; key value
l_idx integer;
begin
...
14. Associative Array
declare
type num_tbl is table of number
index by binary_integer;
l_num_tbl num_tbl; key value
l_idx integer;
begin 1 12
l_num_tbl(1):= 12; 54 5
l_num_tbl(54):= 5;
...
15. Associative Array
declare
type num_tbl is table of number
index by binary_integer;
l_num_tbl num_tbl; key value
l_idx integer;
begin 1 12
l_num_tbl(1):= 12; 3 98
l_num_tbl(54):= 5;
l_num_tbl(3):= 98; 5 3
l_num_tbl(5):= l_num_tbl.count;
l_idx:= l_num_tbl.first; 54 5
...
end;
16. Associative Array
declare
type num_tbl is table of number
index by binary_integer;
l_num_tbl num_tbl; key value
l_idx integer;
begin 2
1 12
l_num_tbl(1):= 12; 3 98
l_num_tbl(54):= 5;
l_num_tbl(3):= 98; 5 3
l_num_tbl(5):= l_num_tbl.count;
10
l_idx:= l_num_tbl.first; 54 5
loop
dbms_output.put_line(l_num_tbl(l_idx));
l_idx:= l_num_tbl.next(l_idx);
exit when l_idx is null;
end loop;
key value
l_num_tbl.delete(2,10); 1 12
dbms_output.put_line(l_num_tbl.count);
end; 54 5
17. Associative Array VARCHAR2 Key
declare
type str_tbl is table of varchar2(40)
index by varchar2(40);
l_str_tbl str_tbl; key value
l_idx varchar2(40);
begin
...
18. Associative Array VARCHAR2 Key
declare
type str_tbl is table of varchar2(40)
index by varchar2(40);
l_str_tbl str_tbl; key value
l_idx varchar2(40);
begin one een
l_str_tbl('one'):= 'een'; two twee
l_str_tbl('two'):= 'twee';
...
19. Associative Array VARCHAR2 Key
declare
type str_tbl is table of varchar2(40)
index by varchar2(40);
l_str_tbl str_tbl; key value
l_idx varchar2(40);
begin four vier
l_str_tbl('one'):= 'een'; one een
l_str_tbl('two'):= 'twee';
l_str_tbl('three'):= 'drie'; three drie
l_str_tbl('four'):= 'vier';
l_idx:= l_str_tbl.first; two twee
...
end;
20. Associative Array VARCHAR2 Key
declare
type str_tbl is table of varchar2(40)
index by varchar2(40);
l_str_tbl str_tbl; key value
l_idx varchar2(40);
begin four vier
l_str_tbl('one'):= ‘een'; o
one een
l_str_tbl('two'):= ‘twee';
l_str_tbl('three'):= 'drie'; three drie
l_str_tbl('four'):= 'vier'; tr
l_idx:= l_str_tbl.first; two twee
loop
dbms_output.put_line(l_str_tbl(l_idx));
l_idx:= l_str_tbl.next(l_idx);
key value
exit when l_idx is null;
end loop; four vier
l_str_tbl.delete('o', 'tr');
dbms_output.put_line(l_str_tbl.count); two twee
end;
21. Retrieval
for idx in emp_t.first .. emp_t.last
loop • Dense
... • Count > 0
end loop;
for idx in 1 .. emp_t.count
loop
• Dense
...
end loop;
idx := emp_t.first;
while idx is not null
loop
•…
...
idx := emp_t.next (idx);
end loop;
23. About Varrays
Has a maximum size, associated with its type.
Can adjust the size in Oracle10g R2.
Part of object model, requiring initialization.
Is always dense; you can only remove elements
from the end of a varray.
Can be defined as a schema level type and used
as a relational table column type.
varray_example.sql
24. Varray
Single dimensioned, always bounded, never
sparse collection of homogeneous elements
SQL and PL/SQL
Can be used as column datatype in a table
Stored “in-line” in same table
Retains its ordering key value
Needs to be initialized and extended
26. Using Varray
declare
type ename_vt is varray (10) of varchar2(10);
ename_t ename_vt;
begin Initialization
ename_t := ename_vt();
ename_t.extend (1);
ename_t(1) := 'Spencer';
...
end;
declare
type ename_vt is varray (10) of varchar2(10);
ename_t ename_vt := ename_vt ('Davis');
begin
...
end; Initialization and
Extending
27. How Variable is the Varray?
Pre 10gR2: VARRAY needed to be recreated.
10gr2 and up: ALTER TYPE MODIFY LIMIT
Only to increase the limit
varraylimit.sql
29. About Nested Tables
Name reflects fact that this collection can be
"nested" inside relational table as a column.
Type can be defined at schema level.
No practical, pre-defined limit on a nested table.
Valid row numbers range from 1 to 231-1.
(i.e. 1 to 2,147,483,647)
Part of object model, requiring initialization.
Is always dense initially, but can become sparse
after deletes.
nested_table_example.sql
30. Nested Tables
Single dimensioned, unbounded, sparse collection
of homogeneous elements
SQL and PL/SQL
Can be used as column datatype in a table
Stored “out-of-line” in a separate table
Initially dense, can be sparse
key value
32. Using Nested Tables
declare
type ename_nt is table of varchar2(10);
ename_t ename_nt;
begin Initialization
ename_t := ename_nt();
ename_t.extend (1);
ename_t(1) := 'Spencer';
...
end;
declare
type ename_nt is table of varchar2(10);
ename_t ename_nt := ename_nt ('Davis');
begin
...
end; Initialization and
Extending
33. Differences
Feature Associative Array Nested Table VArray
SQL – PL/SQL PL/SQL only SQL and PL/SQL SQL and PL/SQL
Dense - Sparse Sparse Initially Dense Dense
Can become sparse
Size ‘Unlimited’ ‘Unlimited’ Limited
Order Unordered Unordered Ordered
Usage Any set of data Any set of data Small sets of data
Use in Table No Yes Yes
34. Bulk Processing in PL/SQL
FORALL
Use with inserts, updates and deletes.
Move data from collections to tables.
BULK COLLECT
Use with implicit and explicit queries.
Move data from tables into collections.
In both cases, the "back back" end processing in the
SQL engine is unchanged.
Same transaction and rollback segment management
Same number of individual SQL statements will be
executed.
But BEFORE and AFTER statement-level triggers only
fire once per FORALL INSERT statements.
statement_trigger_and_forall.sql
35. BULK COLLECT for multi-row querying
SELECT * BULK COLLECT INTO collection FROM table;
FETCH cur BULK COLLECT INTO collection;
Fetch one or more rows into a collection.
Collection is always filled sequentially from index value 1.
Query does not raise NO_DATA_FOUND if no rows are
fetched.
Instead, the collection is empty.
Use FETCH with LIMIT to manage memory.
36. BULK COLLECT for multi-row querying
SELECT * BULK COLLECT INTO collection FROM table;
FETCH cur BULK COLLECT INTO collection;
Fetch one or more rows into a collection.
Collection is always filled sequentially from index value 1.
Query does not raise NO_DATA_FOUND if no rows are
fetched.
Instead, the collection is empty.
Use FETCH with LIMIT to manage memory.
37. Limiting retrieval with BULK COLLECT
If you are certain that your table will never have
more than N rows, use a VARRAY (N) to hold the
fetched data.
If that limit is exceeded, Oracle will raise an
error.
If you do not know in advance how many rows
you might retrieve, you should:
Declare an explicit cursor.
Fetch BULK COLLECT with the LIMIT clause.
38. Details on that LIMIT clause
The limit value can be a literal or a variable.
Use a variable for the limit to give you
maximum flexibility.
With very large volumes of data and small
numbers of batch processes, however, a larger
LIMIT could help.
39. Terminating loops containing BULK COLLECT
LOOP
FETCH my_cursor BULK COLLECT INTO l_collection LIMIT 100;
EXIT WHEN my_cursor%NOTFOUND; BAD IDEA
You will need to break the habit of checking
%NOTFOUND right after the fetch.
You might skip processing some of your data.
Instead, do one of the following:
At the end of the loop, check %NOTFOUND.
Right after fetch, exit when collection.COUNT = 0.
At end of loop, exit when collection.COUNT < limit.
bulklimit_stop.sql
40. When to convert to BULK COLLECT
Prior to Oracle10g, you should convert all multiple row
fetch logic, including cursor for loops, to BULK
COLLECTs.
For Oracle10g and above, leave your cursor for loops in
place if they...
contain no DML operations.
seem to be running fast enough.
Explicit BULK COLLECTs will usually run faster than
cursor for loops optimized to Bulk Collect.
41. Use FORALL for multi-row DML operations
PROCEDURE upd_for_dept (...) IS
BEGIN
FORALL indx IN low_value .. high_value
UPDATE employee
SET salary = newsal_in
WHERE employee_id = list_of_emps (indx);
END;
Binding array
Convert loops that contain inserts, updates or deletes to
FORALL statements.
Header looks identical to a numeric FOR loop.
Implicitly declared integer iterator
At least one "bind array" that uses this iterator as its
index value.
42. More on FORALL
Use any type of collection with FORALL.
One DML statement is allowed per FORALL.
Each FORALL is its own "extended" DML statement.
The collection must be indexed by integer.
The binding array must be sequentially filled.
Unless you use the INDICES OF or VALUES OF clause.
SQL%ROWCOUNT returns total number of rows modified
by entire FORALL.
Unreliable when used with LOG ERRORS.
Use the SQL%BULK_ROWCOUNT cursor attribute to
determine how many rows are modified by each
statement.
bulktiming.sql
bulk_rowcount.sql
43. FORALL and collections of records
Prior to 11g, you cannot reference a field of a record in
FORALL.
You must instead break data into separate collections, or...
You can also perform record-level inserts and updates.
In 11g, this restriction is lifted (but it is an undocumented
feature).
http://technology.amis.nl/blog/2367/implementation-restricted-relaxed-in-oracle-11g
11g_field_of_record.sql
44. INDICES OF and VALUES OF
Prior to Oracle10g R2, the binding arrays in a FORALL
statement must be sequentially filled.
Now, however, you can bind sparse collections by using
INDICES OF and VALUES OF in the FORALL header.
PROCEDURE upd_for_dept (...) IS
BEGIN
FORALL indx IN INDICES OF list_of_emps
UPDATE employee
SET salary = newsal_in
WHERE employee_id = list_of_emps (indx);
10g_indices_of*.sql
10g_values_of*.sql
45. Exception handling and FORALL
When an exception occurs in a DML statement....
That statement is rolled back and the FORALL stops.
All (previous) successful statements are not rolled
back.
Use the SAVE EXCEPTIONS clause to tell Oracle to
continue past exceptions, and save the error information
for later.
Then check the contents of the pseudo-collection of
records, SQL%BULK_EXCEPTIONS.
Two fields: ERROR_INDEX and ERROR_CODE
46. Converting old-fashioned code to bulk
slow-by-slow
Change from integrated, row-by-row approach to
a phased approach.
Phase 1: get the data with BULK COLLECT.
Filling those collections
Phase 2: massage collections so they are ready
for DML operations.
Phase 3: push the data to the database with
FORALL.
cfl_to_bulk_0.sql
cfl_to_bulk_5.sql
10g_indices_of.sql
10g_values_of.sql
47. Bulk Processing Conclusions
Most important performance tuning feature in PL/SQL.
Almost always the fastest way to execute multi-row
SQL operations in PL/SQL.
You trade off increased complexity of code for
dramatically faster execution.
But in Oracle Database 10g and above, the compiler
will automatically optimize cursor FOR loops to
BULK COLLECT efficiency.
No need to convert unless the loop contains DML or
you want to maximally optimize your code.
Watch out for the impact on PGA memory!
53. Table Functions
Table functions are functions that produce
a collection of rows
(either a nested table or a varray)
that can be queried like a physical database table.
You use a table function like the name of a
database table, in the FROM clause of a query.
55. Table Functions
Create a function in PL/SQL
Make sure it returns a collection
Query it using the TABLE() operator
Table functions can be pipelined
(return results as they are produced)
Table functions can be paralellized
56. Table Functions
You can use Table Functions when
Calculations cannot (easily) be done in SQL
You want to take advantage of PL/SQL e.g.
caching or package variables
You want to leverage the power of PL/SQL in
SQL
Make your views more dynamic
57. Resources
Online
tahiti.oracle.com
For all documentation online
www.allthingsoracle.com
o http://allthingsoracle.com/collections-in-oracle-pt-1/
o http://allthingsoracle.com/collections-in-oracle-part-2/
o http://allthingsoracle.com/bulk-processing-in-oracle-part-1/
o http://allthingsoracle.com/bulk-processing-in-oracle-part-2/
Books
Oracle PL/SQL Programming
Chapter 12 (collections) and
chapter 21 (bulk processing)
Oracle PL/SQL for DBAs
Chapter 1 (collections and bulk processing)