Sub topic 15
Pipelined Table Functions
What a pipelined table function does
Assume you know SELECT, PL/SQL loops, collections, and anonymous blocks. A pipelined table function is a PL/SQL function that returns rows one at a time. SQL can read those rows as if they came from a table.
A regular function usually finishes its work and then returns one value. A pipelined function uses PIPE ROW to send each result to the SQL engine immediately. This can reduce memory use and let a query start processing before the function has generated every row.
flowchart TD
A[SQL query] --> B[TABLE function call]
B --> C[Pipelined PL/SQL function]
C --> D[PIPE ROW result 1]
C --> E[PIPE ROW result 2]
C --> F[PIPE ROW result 3]
D --> G[Query processes rows]
E --> G
F --> GDefine the collection and function
The function's return type must be a collection type that SQL can understand. Create that type at the schema level. The simplest example is a nested table of numbers.
CREATE OR REPLACE TYPE number_list AS TABLE OF NUMBER;
/
CREATE OR REPLACE FUNCTION squares (
p_limit IN PLS_INTEGER
) RETURN number_list
PIPELINED
IS
BEGIN
IF p_limit < 1 THEN
RETURN;
END IF;
FOR i IN 1 .. p_limit LOOP
PIPE ROW (i * i);
END LOOP;
RETURN;
END squares;
/PIPELINED marks the function as a row producer. Each PIPE ROW sends one number. The final RETURN ends the function without returning a collection value in the usual way.
Use the function in SQL with the TABLE operator:
SELECT column_value AS square
FROM TABLE(squares(5))
ORDER BY square;The result is:
| SQUARE |
|---|
| 1 |
| 4 |
| 9 |
| 16 |
| 25 |
For a collection containing scalar values, Oracle exposes the value through COLUMN_VALUE. If the collection contains objects, each object attribute becomes a column.
When to use one
Pipelined table functions are useful when a result requires procedural logic that is awkward or inefficient in ordinary SQL. Examples include parsing external data, transforming complex inputs, or combining rows from several sources.
The function can accept normal parameters. You can also join its output with tables:
SELECT e.employee_id, s.square
FROM employees e
CROSS JOIN TABLE(squares(3)) s
WHERE e.department_id = 60;The function is executed as part of the SQL statement, so SQL-call restrictions apply. For example, avoid modifying tables that the surrounding query is reading. Keep the function focused on producing rows.
Common errors
- Forgetting
PIPELINEDcauses the function declaration to be invalid for piped output. - Returning a PL/SQL-only collection type prevents SQL from using the function through
TABLE. - Omitting
TABLE(...)makes Oracle treat the collection as a scalar expression. - Using the wrong
PIPE ROWvalue causes a type mismatch.
Exercise
What does PIPE ROW (i * i) do in the example?
Show answer
It sends one calculated number to the SQL query immediately. The function repeats this operation for each loop iteration.