In Oracle, collections are composite data types used to store and manage multiple values as a single unit. Unlike scalar data types (such as numbers and strings), collections can hold multiple elements, making them useful for handling sets of data. Oracle offers several types of collections, including nested tables, associative arrays (also known as index-by tables), and varrays (variable-size arrays). Here’s a brief description of Oracle collections:
- Nested Tables:
- A nested table is an unordered collection of elements that can have a variable number of elements. You define the type of elements that the nested table can hold, and you can perform operations like insertion, deletion, and querying on the elements.
-- Declare a nested table type TYPE student_list IS TABLE OF VARCHAR2(50); -- Declare a variable of the nested table type students student_list := student_list('Alice', 'Bob', 'Charlie'); -- Accessing elements students(2); -- Retrieves 'Bob'
- Associative Arrays (Index-By Tables):
- Associative arrays, also known as index-by tables or PL/SQL tables, are collections that use a unique key to access their elements. They are particularly useful when you want to associate values with specific keys, similar to dictionaries or hash maps in other programming languages.
-- Declare an associative array type TYPE salary_table IS TABLE OF NUMBER INDEX BY VARCHAR2(50); -- Declare a variable of the associative array type salaries salary_table; -- Assign values using keys salaries('Alice') := 55000; salaries('Bob') := 60000; -- Accessing elements salaries('Alice'); -- Retrieves 55000
- Varrays (Variable-Size Arrays):
- A varray is an ordered collection of elements with a fixed maximum size. The size is determined when you define the varray type, and you cannot exceed this size. Varrays are indexed by integers and behave similar to arrays in many programming languages.
-- Declare a varray type TYPE phone_numbers IS VARRAY(3) OF VARCHAR2(15); -- Declare a variable of the varray type contact_numbers phone_numbers := phone_numbers('555-1234', '555-5678'); -- Accessing elements contact_numbers(2); -- Retrieves '555-5678'
- Use Cases:
- Collections are often used to hold and manipulate sets of data in PL/SQL. They are particularly useful when working with dynamic lists of values, such as employee names, order items, or customer addresses.
- PL/SQL Bulk Operations:
- Collections are essential for PL/SQL bulk operations, where you can perform actions on multiple elements at once, reducing the number of database round-trips and improving performance.
Collections in Oracle provide a flexible and powerful way to work with multiple values in PL/SQL programs. They are instrumental for managing sets of data efficiently, improving code readability, and enabling bulk processing of data, making them a fundamental feature of Oracle’s database programming capabilities.