Returning a Table from an Oracle Function (Concept & Mechanism)
In Oracle, a function cannot directly return a database table.
However, it can return a collection type (a table in memory), which SQL can then treat as a virtual table.
To support this, Oracle requires a structured set of components defined at the SQL level.
1. Row Type (Single Result Row Definition)
A row type describes the structure of one record in the returned result set.
It defines the columns and their data types, similar to a table row.
Purpose:
2. Table Type (Collection of Rows)
A table type defines a list of row-type elements.
This acts as an in-memory table that can hold multiple result rows.
Purpose:
3. Function Returning the Table Type
The function itself returns a value whose type is the table-collection type.
There are two ways the function may return results:
A) Normal (Bulk Return)
Characteristics:
|
Aspect |
Behavior |
|
Memory Use |
Higher (all rows stored before return) |
|
Speed |
Rows appear only after function completes |
|
Good For |
Small datasets, simple logic |
B) Pipelined Return (Streaming Return)
The function streams rows as they are produced, without constructing the whole result in memory.
Characteristics:
|
Aspect |
Behavior |
|
Memory Use |
Very low (no full buffering) |
|
Row Availability |
Immediate — rows returned one-by-one |
|
Performance |
Excellent for large datasets |
|
Good For |
Long-running operations, big tables |
Concept:
Each row is emitted using PIPE ROW, enabling caller to start receiving data instantly.
4. Querying the Function Output
SQL uses the TABLE(...) operator to treat the returned collection as if it were a regular relational table.
This allows:
The database effectively converts the in-memory list into a row source for the SQL optimizer.
Summary: What Each Component Does
|
Component |
Role |
|
Row Type |
Defines one row structure for the returned result |
|
Table Type |
Defines the full result set as a collection of rows |
|
Normal Return Function |
Returns all rows at once (buffered) |
|
Pipelined Function |
Streams rows progressively (efficient) |
|
TABLE(...) Operator |
Makes the returned collection usable in SQL queries |
When to Choose Which Return Style
|
Situation |
Best Method |
|
Small or simple result sets |
Normal return |
|
Large datasets / streaming / performance-critical queries |
Pipelined return |