Open In App

PL/SQL Nested Table

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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-PlSQL
Nested Table in PLSQL

Explanation:

  • 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 PLSQL
Nested TAbles in PLSQL

Explanation:

  • 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-Tables
PLSQL NESTED Tables

Explanation:

  • 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.

Next Article

Similar Reads