PL/SQL, Oracle's procedural extension of SQL, offers powerful capabilities for managing and processing data within the database. One of its key features is support for complex data structures, including collections like nested tables. A nested table in PL/SQL is a dynamic, array-like data structure that allows you to store multiple elements of the same data type in a single variable. Every PL/SQL query contains BEGIN, and END keywords. We can nest blocks in PL/SQL. It supports anonymous blocks and named blocks. Anonymous blocks are not stored in the database while named blocks are stored.
Here, we’ll explore nested tables in PL/SQL. We’ll look at what they are, how they work, and what they can be used for.
PL/SQL block Structure
A typical PL/SQL block has the following structure:
-- Declaration Section
DECLARE
-- Variable and nested table declarations
BEGIN
-- Execution Section
-- Statements to perform operations
EXCEPTION
-- Exception Handling Section
-- Optional: Handle any runtime errors
END;
What are PL/SQL Nested Tables?
Nested tables in PL/SQL are data structures that function like arrays, allowing you to store multiple values in a single column. They are stored in a database. However, unlike traditional arrays, nested tables in PL/SQL are dynamic i.e. the amount of memory utilized can increase or decrease as per use. They allow you to work on variable amounts of data dynamically. They are used when an unknown number of elements are to be stored. Elements of any datatype can be stored in a nested table.
PL/SQL nested tables are stored in the database and can hold elements of any data type. They are particularly useful when dealing with complex data structures and dynamic datasets. Two main types of nested tables exist:
- Bounded Nested Tables: Have a fixed size.
- Unbounded Nested Tables: Are dynamic and can grow or shrink based on usage
Syntax of PL/SQL nested tables
DECLARE
--DECLARE THE NESTED TABLE TYPE
TYPE nested_table_type IS TABLE OF data_type;
--Declare variable of the nested table type
variable nested_table_type;
BEGIN
--initialize the variable
variable := nested_table_type( element1,element2 .....elementn)
-- Perform the required operations
-- free up the allocated memory
variable : =NULL;
END;
- The nested table type is declared using the TYPE keyword.
- The variable is created using IS TABLE OF.
Working with PL/SQL Nested Tables
1. Declaring a Nested Table Variable
A nested table in oracle is declared in the declaration section like cursors or procedure. The datatype is declared along with the name of the nested table.
TYPE nested_table_type IS TABLE OF data_type;
variable nested_table_type;
2. Initializing a Nested Table
When a variable is declared using the nested table type it is initialized to NULL. Constructor initializes the value to the variable.
Syntax:
variable_of_nested_table := nested_table_type();
3. Add Elements to a Nested Table
Elements can be added to nested tables using the EXTEND keyword or the constructor. Elements are added in the execution section of the pl/sql block.
Syntax (Using EXTEND):
--using EXTEND keyword
BEGIN
nested_table_type_variable.EXTEND;
nested_table_type_variable(1) := value1;
nested_table_type_variable(2) := value2;
Syntax (Using Parameterized Constructor):
--using parameterized constructor
BEGIN
nested_table_type_variable := nested_table_type(value1,value2 .....);
Examples of PL/SQL Nested Table
Example 1: Accessing Elements by Their Indexes
Indexes in PL/SQL nested tables start from 1. Elements are accessed by specifying the index.
Syntax:
SET SERVEROUTPUT ON;
DECLARE
-- DECALRE NESTED TABLE AND THE VARIABLE
BEGIN
DBMS_OUTPUT.PUTLINE(nested_table_variable(1 ));
END;
The first element of the nested table is printed by specifying the index with the variable. After putting all the mentioned things together we can perform operation on nested table.
Query:
SET SERVEROUTPUT ON;
DECLARE
TYPE First_nested_table IS TABLE OF NUMBER;
example_one First_nested_table;
BEGIN
-- Initialize the nested table
example_one := First_nested_table(1, 2, 3, 4, 5);
FOR i IN example_one.FIRST .. example_one.LAST LOOP
DBMS_OUTPUT.PUT_LINE('Element ' || i || ': ' || example_one(i));
END LOOP;
-- Free up memory
example_one := NULL;
END;
Output:
Nested Table in PLSQLExplanation:
- The nested table numbers is initialized with a set of values.
- A FOR loop is used to iterate from the first element to the last.
- DBMS_OUTPUT.PUT_LINE displays each element's index and value
Example 2: Initializing and Printing Elements of a Nested Table in PL/SQL
This example demonstrates initializing and printing elements of a nested table containing strings.
Query
SET SERVEROUTPUT ON;
DECLARE
TYPE First_nested_table IS TABLE OF VARCHAR2(20);
example_one First_nested_table;
BEGIN
-- Initialize the nested table
example_one := First_nested_table('ONE','TWO','THREE','FOUR');
FOR i IN example_one.FIRST .. example_one.LAST LOOP
DBMS_OUTPUT.PUT_LINE('Element ' || i || ': ' || example_one(i));
END LOOP;
-- Free up memory
example_one := NULL;
END;
/
Output:
Nested TAbles in PLSQLExplanation:
- A nested table strings is initialized with four string values.
- The FOR loop iterates over each element to print the values.
Example 3: Addition of the Elements of the Nested Tables
This example illustrates performing an element-wise addition of two nested tables and storing the result in a new table.
Query:
SET SERVEROUTPUT ON;
DECLARE
TYPE NST_TBL IS TABLE OF NUMBER;
-- Declare two nested tables
var1 NST_TBL := NST_TBL(1, 2);
var2 NST_TBL := NST_TBL(3, 4);
-- result nested table
result NST_TBL;
BEGIN
result := NST_TBL();
result.EXTEND(var1.COUNT);
--addition of the elements
FOR i IN 1..var1.LAST LOOP
result(i) := var1(i) + var2(i);
END LOOP;
-- Display result of addition
DBMS_OUTPUT.PUT_LINE('Result(1): ' || result(1) || ' Result(2): ' || result(2));
END;
/
Output:
PLSQL NESTED TablesExplanation:
- Two nested tables table1 and table2 are initialized.
- The result nested table is created and populated with the sum of corresponding elements from table1 and table2.
Important Points About PL/SQL Nested Table
- Unlike arrays in some programming languages that start indexing at 0, nested tables in PL/SQL start indexing from 1.
- When used in PL/SQL blocks, nested tables exist only in memory. However, they can be stored in the database as columns of table types, allowing for persistence.
- Accessing an element outside the range of existing indexes (e.g., negative index or an index greater than the number of elements) raises a SUBSCRIPT_BEYOND_COUNT exception.
- PL/SQL automatically manages the memory for nested tables. However, if the table grows too large, it may impact performance, especially if operations involve many elements.
Similar Reads
PL/SQL Derived Tables
Derived Tables in PL/SQL are temporary result sets that are created within the execution of a SQL statement. These are essential tools that allow developers to create temporary result sets within SQL statements. This feature enables complex queries to be simplified and enhances readability by encaps
4 min read
SQL CREATE TABLE
In SQL, creating a table is one of the most essential tasks for structuring your database. The CREATE TABLE statement defines the structure of the database table, specifying column names, data types, and constraints such as PRIMARY KEY, NOT NULL, and CHECK. Mastering this statement is fundamental to
5 min read
MySQL Derived Table
Structured Query Language (SQL) is a powerful tool for managing and querying relational databases, and MySQL is one of the most widely used database management systems. In MySQL, derived tables offer a flexible and efficient way to manipulate and analyze data within a query. In this article, we will
5 min read
SQLite Create Table
SQLite is a database engine. It does not require any server to process queries. It is a kind of software library that develops embedded software for television, smartphones, and so on. It can be used as a temporary dataset to get some data within the application due to its efficient nature. It is pr
2 min read
PL/SQL CREATE TABLE Statement
PL/SQL CREATE TABLE statement is a fundamental aspect of database design and allows users to define the structure of new tables, including columns, data types, and constraints. This statement is crucial in organizing data effectively within a database and providing a blueprint for how data should be
4 min read
PL/SQL INSERT Statement
The PL/SQL INSERT statement is vital for adding new records to a database table. By specifying the table's name and providing values for its columns, users can populate their database with essential information. This functionality enables efficient data entry and ensures the completeness of datasets
3 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE statement is used to define a new table within a database. It allows us to specify the table's structure, including column names, data types, and constraints, ensuring data integrity and consistency. Understanding the PostgreSQL table creation process is essential for
5 min read
PL/SQL DELETE Statement
In PL/SQL(Procedural Language/Structured Query Language), the DELETE statement is the powerful command used to remove one or more records from the database table. It is an essential part of database management and enables the users to efficiently manage and maintain the data integrity by selectively
7 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
SQL - Show Tables
When we are working with the SQL (Structured Query Language) Server database, understanding its structure is one of the fundamental tasks which is includes knowing which tables are available. Whether you are the database administrator, a developer or an analyst being able to list the tables within t
3 min read