In PL/SQL, an Associative Array (also known as an index-by table) is a collection of key-value pairs where each key is unique, allowing for efficient retrieval of the associated value. Associative arrays are particularly useful when we need to store data in a non-contiguous manner, enabling us to index elements with non-integer or sparse keys.
PL/SQL Associative Array is especially useful for managing sparse datasets or non-sequential data. In this article, we will explain how to create, use, and manipulate associative arrays in PL/SQL, with clear examples to demonstrate their flexibility.
PL/SQL Associative Array
An associative array can be indexed by an integer or a string. It allows for fast lookups and dynamic data manipulation without defining a fixed size. Unlike VARRAYs and nested tables, associative arrays do not require consecutive memory allocation. They are highly efficient for performing lookups or managing non-contiguous data without needing to define a fixed array size.
Syntax:
TYPE array_name IS TABLE OF element_type INDEX BY index_type;
key terms
- array_name: The name of the associative array.
- element_type: The data type of the elements stored in the array.
- index_type: The data type of the index (commonly
PLS_INTEGER
or VARCHAR2
).
Example 1: Associative Array with Integer Index
In this example, we will demonstrate how to use an associative array with an integer index, where employee IDs are used as unique keys. The array stores employee salaries, allowing efficient retrieval of salary data using the employee ID. This approach is ideal for managing data where the index is numeric and non-contiguous.
Query:
DECLARE
-- Declare an associative array type
TYPE employee_salary IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
-- Declare a variable of this type
emp_salaries employee_salary;
BEGIN
-- Insert data into the associative array
emp_salaries(101) := 50000;
emp_salaries(102) := 60000;
emp_salaries(103) := 55000;
-- Access and display the data
DBMS_OUTPUT.PUT_LINE('Salary of employee 101: ' || emp_salaries(101));
DBMS_OUTPUT.PUT_LINE('Salary of employee 102: ' || emp_salaries(102));
DBMS_OUTPUT.PUT_LINE('Salary of employee 103: ' || emp_salaries(103));
END;
Output
Employee ID | Salary |
---|
101 | 50000 |
102 | 60000 |
103 | 55000 |
Explanation:
- The associative array
employee_salary
is declared with a key type of PLS_INTEGER
and stores NUMBER
values representing employee salaries.
- Values are inserted into the array using the employee ID as the index.
- The
DBMS_OUTPUT.PUT_LINE
function displays the salaries for each respective employee.
Example 2: Associative Array with String Index
This example illustrates how to use an associative array with a string index, where product names serve as the keys. The array stores product prices, making it easy to retrieve the price of each product using its name as the index. Associative arrays indexed by strings are useful for mapping descriptive labels to data values.
Query:
DECLARE
-- Declare an associative array type
TYPE product_price IS TABLE OF NUMBER INDEX BY VARCHAR2(50);
-- Declare a variable of this type
product_prices product_price;
BEGIN
-- Insert data into the associative array
product_prices('Laptop') := 1200;
product_prices('Smartphone') := 800;
product_prices('Tablet') := 400;
-- Access and display the data
DBMS_OUTPUT.PUT_LINE('Price of Laptop: ' || product_prices('Laptop'));
DBMS_OUTPUT.PUT_LINE('Price of Smartphone: ' || product_prices('Smartphone'));
DBMS_OUTPUT.PUT_LINE('Price of Tablet: ' || product_prices('Tablet'));
END;
Output
Product | Price |
---|
Laptop | 1200 |
Smartphone | 800 |
Tablet | 400 |
Explanation:
- The associative array
product_price
is declared with a key type of VARCHAR2
(50)
and stores NUMBER
values representing product prices.
- Products and their prices are inserted into the array using the product name as the index.
- The
DBMS_OUTPUT.PUT_LINE
function displays the prices for each respective product.
Benefits of Associative Arrays in PL/SQL
- Dynamic Sizing: Associative arrays grow dynamically without needing predefined size constraints.
- Efficient Lookups: Fast retrieval based on unique keys (integers or strings) ensures quick access to data.
- Sparse Data Handling: Ideal for handling non-contiguous data where only specific indices contain values.
- Flexible Indexing: Can be indexed using either integers or strings, making them versatile for different use cases.
Limitations of Associative Arrays
- Memory Restrictions: Associative arrays reside in PL/SQL memory, meaning they are not stored in the database permanently.
- No Multi-dimensional Arrays: Associative arrays cannot directly support multi-dimensional indexing.
- Not Persistent: Data stored in associative arrays is lost after the PL/SQL block execution ends.
Conclusion
Associative arrays in PL/SQL provide a powerful and flexible way to manage collections of data without the constraints of fixed indexing or contiguous storage. They are particularly useful for where dynamic data retrieval is required, allowing for efficient data manipulation and access. PL/SQL Associative Array can optimize code's efficiency when dealing with dynamic datasets.
Similar Reads
Associative Arrays in PHP
Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject's names as the keys in our associative array, and the value woul
3 min read
PL/SQL Arrays
PL/SQL, an extension of SQL developed through Oracle, empowers builders with robust programming skills for powerful database management. Among its many capabilities, arrays stand out as an essential tool for organizing and manipulating data correctly. In this article, we'll dive deep into the secto
5 min read
Sort an Associative Array by Key in PHP
Given an Associative Array, the task is to sort the associative array by its keys in PHP. There are different methods to sort Associative Array by keys, these are described below: Table of Content Using ksort() FunctionUsing uksort() FunctionConverting to a Regular Array for SortingUsing array_multi
3 min read
PL/SQL Cross Join
Combining data from several tables is an ordinary procedure in the field of relational databases. The Cross Join is one of the several table joining techniques offered by PL/SQL, Oracle's procedural SQL extension. To improve your comprehension, this article will provide you with an introduction to C
7 min read
PL/SQL Aggregate Function
In PL/SQL, aggregate functions play an important role in summarizing and analyzing data from large datasets. These built-in SQL functions perform calculations on a set of values and return a single result, making them invaluable for tasks like calculating totals, averages, and identifying the highes
6 min read
PL/SQL AND Operator
The PL/SQL AND operator is used to combine multiple conditions in a WHERE clause of an SQL query. It allows you to refine your query by ensuring that all specified conditions are met. AND queries which help in filtering data more precisely and can be crucial for retrieving accurate results from a da
7 min read
PL/SQL Outer Join
In SQL, joins are used to retrieve data from two or more tables based on a related column. Joins can be categorized into different types: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, etc. In this article, we will learn about OUTER JOIN in PL/SQL, including its types, syntax, use cases, and ex
6 min read
PostgreSQL - ARRAY_AGG() Function
The PostgreSQL ARRAY_AGG function is a aggregate function that allows users to combine values from multiple rows into an array. This function is particularly useful when managing grouped data and returning multiple values in a single row. In this article, We will learn about the What is PostgreSQL A
4 min read
PostgreSQL - Array Data Type
PostgreSQL provides an advanced and flexible feature known as the Array Data Type, which allows us to store multiple values in a single column. Arrays in PostgreSQL can be used with all built-in data types and even user-defined types, enabling a wide range of use cases. In this article, we will expl
4 min read
PL/SQL Insert Into
PL/SQL (Procedural Language/Structured Query Language) is Oracle's procedural extension to SQL. It allows us to write complex queries and scripts that include procedural logic, control structures, and error handling. The INSERT INTO statement in PL/SQL is essential for adding new rows of data to tab
6 min read