In Oracle PL/SQL, handling collections of data is a common requirement for many applications, whether it’s storing a list of values, managing configurations, or processing data in bulk. Among the various collection types available, VARRAY (variable-sized array) stands out as a practical option for cases where a fixed-size, ordered collection is needed. Unlike other collection types like nested tables and associative arrays, VARRAYs provide a structured way to manage data with a predetermined number of elements, making them suitable for scenarios where the data set's size is known beforehand.
In this article, we will cover everything you need to know about using VARRAYs in Oracle PL/SQL, including declaring and initializing them, accessing elements, and performing operations like adding or deleting elements.
What is a VARRAY?
A VARRAY (variable-sized array) is a one-dimensional collection that allows you to store an ordered set of elements of similar data types. It is best suited for cases where the number of elements is known and remains within a fixed range. VARRAYs are nonsparse, meaning they do not have gaps between elements, and the order of elements is always maintained. Some key characteristics of VARRAYs are:
- Fixed Size Limit: The maximum number of elements is defined when creating the VARRAY type.
- Ordered Collection: The order in which elements are added is preserved.
- Nonsparse Structure: No gaps are allowed between elements.
Different Operations on PL/SQL VARRAYS
Let us look at the different operations that can be done using the Varrays in Oracle PL/SQL.
1. Declare and Initialize VARRAY variables
To use a VARRAY in PL/SQL, you need to follow two steps: create a VARRAY type and then declare a variable of that type.
Step 1: Create a VARRAY Type
The syntax to create a VARRAY type is:
-- To Create a VARRAY type here
TYPE SampleVARRAY IS VARRAY (3) of VARCHAR (10);
- SampleVARRAY: Name of the VARRAY type.
- 3: Maximum number of elements allowed in the VARRAY.
- VARCHAR2(10): Data type of the elements.
Step 2: Declare and Initialize a VARRAY Variable
After creating the VARRAY type, you can declare a variable of that type and initialize it:
-- To Declare a variable which is of VARRAY type
DECLARE
myVarray SampleVARRAY := SampleVARRAY('Ramesh', 'Kamlesh', 'Shyam');
2. Accessing VARRAY Elements
In VARRAYs, we can access elements easily like simple arrays. We can access single element that we want to access or also we can access all the elements by using loops. Syntax for accessing VARRAY elements is:
Accessing Single Element
To access a specific element, use the index number within parentheses.
DECLARE
myVarray SampleVARRAY := SampleVARRAY('Ramesh', 'Kamlesh', 'Shyam');
Begin
-- Accessing elements by index
dbms_output.PUT_LINE('This is First element: ' || myVarray(1));
End;
Output:
Accessing first elementAccessing Multiple Elements
You can iterate through all the elements using a loop.
DECLARE
myVarray SampleVARRAY := SampleVARRAY('Ramesh', 'Kamlesh', 'Shyam');
Begin
-- Accessing alll the elements
FOR i IN 1.. myVarray.COUNT loop
dbms_output.PUT_LINE('This is element ' || i || ':' || myVarray(i));
END LOOP;
End;
Output:
Accessing all elements by using loop3. Deleting Elements from VARRAY
To delete elements in VARRAYs we simply need to mention the element that we want to delete from VARRAY in DELETE(_). Syntax to delete elements from VARRAY is:
DECLARE
myVarray SampleVARRAY := SampleVARRAY('Ramesh', 'Kamlesh', 'Shyam');
Begin
-- this will delete3rd element
myVarray.DELETE(3);
End;
Output:
After deletion 4. Add More Elements to VARRAY
Consider we have created a VARRAY and now we want to add some more elements in it so this can be done by using the EXTEND keyword. Which will extend the VARRAY size by one. If we want to extend VARRAY size by more than one then we can simply mention that size in it as EXTEND(4). This will extend VARRAY by four.
The syntax to add an element is:
DECLARE
myVarray SampleVARRAY := SampleVARRAY('Ramesh', 'Kamlesh', 'Shyam');
Begin
-- this will extend VARRAY by one
myVarray.Extend;
-- this will add 'Pankaj' at index 4
myVarray(4) := 'Pankaj';
End;
Output:
Adding one more elementImportant Points About PL/SQL VARRAY
- The maximum number of elements for a VARRAY is defined at the time of creation and cannot be changed later. If you need to increase the size, you'll have to redefine the VARRAY type and update any dependent code.
- In Oracle databases, VARRAYs are stored as a single column in a table, which makes them ideal for preserving the order of elements.
- Unlike nested tables, VARRAYs cannot have gaps in their indexing. If you try to reference an index that doesn’t exist, you’ll encounter an exception.
- To remove elements, you must manually set them to NULL or create a new VARRAY without the unwanted elements.
Similar Reads
PL/SQL VIEW
In Oracle PL/SQL, views are a powerful way to manage data access and simplify complex queries. A view is essentially a virtual table that presents data from one or more tables using a stored query. Unlike physical tables, views do not store the data themselves; they dynamically retrieve data based o
4 min read
PL/SQL Tutorial
Explore this PL/SQL tutorial to effortlessly learn PL/SQL â It is perfect for beginners and experienced ones. Whether you're new to it or diving deep, this interactive guide simplifies database programming.Learn hands-on with practical examples, making your journey fun and effective. Learn PL/SQL's
8 min read
PL/SQL Strings
We will learn several types of strings, the syntax for declaring a string variable, and then utilizing it in a PL/SQL code block. In PL/SQL, a string is a sequence of characters with an optimal size parameter. Strings are sequences of characters, and PL/SQL provides a rich set of functions and opera
6 min read
PostgreSQL - Variables
PostgreSQL, one of the most powerful and advanced open-source relational database management systems, provides robust support for procedural programming through its PL/pgSQL language. A fundamental aspect of PL/pgSQL is the use of variables that play a crucial role in storing temporary data and faci
4 min read
PL/SQL | User Input
Prerequisite - PL/SQL Introduction In PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input for different data types. Consider, following table: Table: GFG id author likes 1 sam 10 2 maria 30 3 ria 40 Following queries will create a new table named GF
2 min read
PL/SQL Subqueries
PL/SQL subqueries are powerful SQL features that allow for the nesting of one query inside another for dynamic data retrieval. They have extensive applications when complex problems are to be solved by reducing them into smaller, more manageable queries. The inner query, usually called the subquery,
9 min read
PL/ SQL Data Types
PL/SQL (Procedural Language/Structured Query Language) is a procedural extension language for SQL used specifically for the Oracle database to ease the management of data and the flow of operations. A core feature of PL/SQL is its diverse set of data types, designed to handle everything from simple
6 min read
PL/SQL Copy Table
Copying tables in PL/SQL is a common task in database management. It involves duplicating the structure and data of an existing table into a new one. This operation can be accomplished using the CREATE TABLE AS SELECT statement, which allows for the creation of a new table based on the result set of
3 min read
PL/SQL CREATE VIEW
PL/SQL CREATE VIEW is a statement used to create a virtual table based on the result of a query. Views in PL/SQL allow users to access and manipulate data stored in one or more underlying tables as if it were a single table. In this article, We will learn about the PL/SQL CREATE VIEW by understandin
3 min read
Perl | Variables
Variables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, deci
4 min read