Sub topic 15
Pipelined Table Functions
This chapter assumes you can write stored functions, call them from SQL, and use collection types such as nested tables. It uses the employees table from earlier chapters. You need the CREATE TYPE privilege as well as CREATE PROCEDURE.
What a pipelined table function is
A table function returns a collection that a query reads like a table, using SELECT ... FROM TABLE(my_function(...)). A regular table function builds the whole collection in memory and returns it in one piece. The query sees no rows until the function finishes.
A pipelined table function returns rows one at a time as it produces them. The PIPE ROW statement hands a row to the consumer and the function continues. This has three effects:
- The consumer can start working on the first row before the last one exists.
- The function never holds the full result in memory.
- The function can stop early if the consumer stops asking for rows.
| Aspect | Regular table function | Pipelined table function |
|---|---|---|
| How rows are returned | `RETURN collection_variable` | `PIPE ROW (...)` per row, then an empty `RETURN` |
| Memory use | Whole collection held in the session | One row at a time |
| First row available | After the function ends | As soon as the first `PIPE ROW` runs |
| Declaration | `RETURN my_tab_t` | `RETURN my_tab_t PIPELINED` |
How rows flow
The function is a producer and the SQL engine is the consumer. They hand rows back and forth during one statement.
A first pipelined function
A pipelined function must declare a collection type as its return type. The type must exist at schema level, or in a package specification on recent Oracle versions. The examples use schema-level types.
First define the row type and the collection type.
CREATE OR REPLACE TYPE emp_row_t AS OBJECT (
employee_id NUMBER,
full_name VARCHAR2(100),
salary NUMBER
);
/
CREATE OR REPLACE TYPE emp_tab_t AS TABLE OF emp_row_t;
/Then write the function.
CREATE OR REPLACE FUNCTION emps_in_dept (
p_department_id IN employees.department_id%TYPE
) RETURN emp_tab_t PIPELINED AS
BEGIN
FOR r IN (
SELECT employee_id,
first_name || ' ' || last_name AS full_name,
salary
FROM employees
WHERE department_id = p_department_id
) LOOP
PIPE ROW (emp_row_t(r.employee_id, r.full_name, r.salary));
END LOOP;
RETURN;
END emps_in_dept;
/Query it like a table:
SELECT employee_id, full_name, salary
FROM TABLE(emps_in_dept(60))
WHERE salary > 5000
ORDER BY salary DESC;Three details matter here:
- The function body contains no collection variable.
PIPE ROWtakes an instance of the collection's element type. RETURN;has no expression. WritingRETURN something;in a pipelined function is a compile error.- Because the result is a table source, you can filter it, join it, aggregate it, or use it in a subquery like any other row source.
Collections of scalars
If you need a single column, the element type can be a scalar. Oracle names that column COLUMN_VALUE.
CREATE OR REPLACE TYPE date_tab_t AS TABLE OF DATE;
/
CREATE OR REPLACE FUNCTION date_range (
p_start IN DATE,
p_end IN DATE
) RETURN date_tab_t PIPELINED AS
BEGIN
FOR i IN 0 .. TRUNC(p_end) - TRUNC(p_start) LOOP
PIPE ROW (TRUNC(p_start) + i);
END LOOP;
RETURN;
END date_range;
/
SELECT COLUMN_VALUE AS day
FROM TABLE(date_range(DATE '2026-01-01', DATE '2026-01-05'));This is a common way to generate a calendar of dates, for example to left-join against sparse data so that days with no activity still appear.
Transforming a stream of rows
A pipelined function can take a cursor as input and pipe out a transformed version of each row. This turns the function into a stage in a pipeline. The CURSOR(...) expression in the query passes the rows in.
CREATE OR REPLACE FUNCTION upper_names (
p_cur IN SYS_REFCURSOR
) RETURN emp_tab_t PIPELINED AS
v_id employees.employee_id%TYPE;
v_name VARCHAR2(100);
v_sal employees.salary%TYPE;
BEGIN
LOOP
FETCH p_cur INTO v_id, v_name, v_sal;
EXIT WHEN p_cur%NOTFOUND;
PIPE ROW (emp_row_t(v_id, UPPER(v_name), v_sal));
END LOOP;
CLOSE p_cur;
RETURN;
END upper_names;
/
SELECT *
FROM TABLE(upper_names(CURSOR(
SELECT employee_id,
first_name || ' ' || last_name,
salary
FROM employees
WHERE department_id = 60)));The fetch list must match the columns in the CURSOR expression in number and type. A mismatch fails at run time, not at compile time, because SYS_REFCURSOR is weakly typed. A strongly typed REF CURSOR declared in a package moves that check to compile time, but you then have to maintain the package type.
You can chain stages by nesting: pass CURSOR(SELECT * FROM TABLE(stage_one(...))) into a second function. Each stage then pulls rows from the previous one as it needs them.
Stopping early
A consumer may stop reading before the function ends, for example with FETCH FIRST 3 ROWS ONLY or WHERE ROWNUM <= 3. When that happens, Oracle raises the predefined exception NO_DATA_NEEDED inside the function at the PIPE ROW call that cannot continue.
SELECT COLUMN_VALUE AS day
FROM TABLE(date_range(DATE '2026-01-01', DATE '2030-12-31'))
FETCH FIRST 3 ROWS ONLY;Without early termination this function would produce about 1,800 rows. With it, only the first three PIPE ROW calls complete.
If the function holds resources such as an open cursor or file handle, handle NO_DATA_NEEDED and release them. Do not let a WHEN OTHERS handler swallow it. If you must catch everything, name NO_DATA_NEEDED in its own handler first:
EXCEPTION
WHEN NO_DATA_NEEDED THEN
-- close cursors, release resources
RETURN;Restrictions and gotchas
- Return type. The return type must be a collection type. It cannot be a plain record or a
%ROWTYPE. - Parameters. A function called from SQL cannot have
OUTorIN OUTparameters. This follows the general rule for functions in SQL statements. - DML. A function called inside a query cannot perform DML on the tables it is reading. Writing to other tables needs an autonomous transaction, which has its own commit rules.
- Row-level SQL cost. Each query against the function runs its body again. Do not call it in a correlated subquery for thousands of outer rows unless each call is cheap.
- Optimizer estimates. The optimizer cannot see inside the function, so it uses a default guess for the number of rows returned. For large results this can lead to poor join choices. Check the plan, and consider
DBMS_STATSextensions or theCARDINALITYhint if estimates matter. - Parallelism. A pipelined function can run in parallel if you declare it with
PARALLEL_ENABLEand give it a cursor parameter with aPARTITION BYclause. This is a specialized feature that needs careful testing.
When to use one
Use a pipelined function when you want to:
- expose procedural logic, such as parsing or a multi-step calculation, as a queryable row source
- generate rows that no table holds, such as date series or split strings
- process very large result sets without holding them all in session memory
Prefer a plain SQL query, or a view, when the logic fits in one statement. SQL lets the optimizer see the whole query. A pipelined function hides its internals from the optimizer and switches between the SQL engine and the PL/SQL engine on each row.
Exercise
You write a pipelined function and end it with RETURN v_result;, where v_result is a collection you filled in a loop. The function fails to compile. What are the two corrections needed to make it a proper pipelined function?
Show answer
Replace the loop that fills the collection with a PIPE ROW (...) call for each row, and change the final statement to a plain RETURN; with no expression. Also remove the v_result variable if nothing else uses it. A pipelined function sends each row with PIPE ROW and ends with an empty RETURN.
Exercise
A query uses WHERE ROWNUM <= 10 on a pipelined function that opens a cursor and has EXCEPTION WHEN OTHERS THEN NULL;. Why is this handler a problem, and how do you fix it?
Show answer
When the consumer stops after 10 rows, Oracle raises NO_DATA_NEEDED inside the function. The WHEN OTHERS THEN NULL handler catches it, so the function does not stop cleanly and the cursor may stay open. Add WHEN NO_DATA_NEEDED THEN before WHEN OTHERS, close the cursor there, and end with RETURN;.