Sub topic 12
Batch fetching with BULK COLLECT and LIMIT
This chapter assumes you can declare, open, fetch from and close an explicit cursor. It also assumes you know %ROWTYPE, the cursor FOR loop, and basic PL/SQL exception handling. You should also know what a collection is, meaning a PL/SQL variable that holds many values under one name.
Why row-by-row fetching is slow
A cursor FOR loop or a FETCH ... INTO loop reads one row at a time. PL/SQL runs inside the PL/SQL engine. SQL runs inside the SQL engine. Each time the loop needs a row, control passes from one engine to the other. This is called a context switch. One switch per row is cheap, but with a million rows it becomes a measurable cost.
BULK COLLECT lets one FETCH return many rows. Oracle fills a collection with all of them in a single switch. Fewer switches means less overhead.
(Oracle's optimizer already rewrites some cursor FOR loops to fetch 100 rows at a time behind the scenes. This applies when the compilation setting PLSQL_OPTIMIZE_LEVEL is 2 or higher, which is the default. Do not rely on that when you need to control batch size or when the loop body does DML on each row.)
BULK COLLECT without LIMIT
The simplest form uses SELECT ... BULK COLLECT INTO.
DECLARE
TYPE t_name_tab IS TABLE OF employees.last_name%TYPE;
l_names t_name_tab;
BEGIN
SELECT last_name
BULK COLLECT INTO l_names
FROM employees
WHERE department_id = 50
ORDER BY last_name;
DBMS_OUTPUT.PUT_LINE(l_names.COUNT || ' names fetched');
FOR i IN 1 .. l_names.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(l_names(i));
END LOOP;
END;
/Three points about this form:
- Oracle initializes and extends the collection for you. You do not call
EXTEND. - If the query returns no rows, no exception is raised. The collection is simply empty and
COUNTis 0. This differs from a plainSELECT INTO, which raisesNO_DATA_FOUND. - Oracle loads every row into memory at once.
The last point is the danger. The collection lives in the session's private memory (the PGA). A query that returns ten million rows can use gigabytes and may fail with an out-of-memory error or slow the whole server. Use unbounded BULK COLLECT only when you know the result set is small.
Bounding memory with LIMIT
LIMIT solves the memory problem. It works only with FETCH on an explicit cursor, not with SELECT ... BULK COLLECT INTO. Each FETCH retrieves at most the number of rows you name, so memory use stays constant however large the table is.
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary FROM employees;
TYPE t_emp_tab IS TABLE OF c_emp%ROWTYPE;
l_emps t_emp_tab;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp BULK COLLECT INTO l_emps LIMIT 100;
EXIT WHEN l_emps.COUNT = 0;
FOR i IN 1 .. l_emps.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(l_emps(i).employee_id || ': ' || l_emps(i).salary);
END LOOP;
END LOOP;
CLOSE c_emp;
END;
/Here is what happens on each pass:
FETCH ... LIMIT 100replaces the contents ofl_empswith the next batch of up to 100 rows. Oracle clears the previous batch first.- When the cursor has fewer than 100 rows left, the fetch returns just those rows.
- When the cursor is exhausted, the fetch returns zero rows and the collection is empty.
EXIT WHEN l_emps.COUNT = 0ends the loop.
The cursor's %ROWCOUNT keeps a running total of rows fetched across all batches. That is useful for progress reporting.
The exit-condition trap
The most common bug with LIMIT is choosing the wrong exit test. In a one-row-at-a-time loop you write EXIT WHEN c%NOTFOUND straight after the fetch. With bulk fetches that test is dangerous.
Suppose the table has 250 rows and the limit is 100. The third fetch returns 50 rows, fewer than the limit. Oracle sets %NOTFOUND to true on that fetch, because the cursor ran out of rows. If you exit immediately, you skip the last 50 rows without any error.
There are two safe patterns.
Pattern 1: test COUNT right after the fetch. This is the one shown above. It processes the partial batch, then exits on the next fetch when the collection is empty. It costs one extra fetch that returns nothing.
Pattern 2: process first, then test %NOTFOUND at the bottom of the loop.
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary FROM employees;
TYPE t_emp_tab IS TABLE OF c_emp%ROWTYPE;
l_emps t_emp_tab;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp BULK COLLECT INTO l_emps LIMIT 100;
FOR i IN 1 .. l_emps.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(l_emps(i).employee_id || ': ' || l_emps(i).salary);
END LOOP;
EXIT WHEN c_emp%NOTFOUND;
END LOOP;
CLOSE c_emp;
END;
/When the collection is empty, FOR i IN 1 .. 0 does not execute, so an empty final batch is harmless. Pattern 1 is easier to read and is the usual recommendation.
Choosing the LIMIT value
There is no universal best number. Values between 100 and 1000 work well for most workloads. The gain comes from the first few dozen rows per batch, and returns diminish quickly. A very large limit brings back the memory problem. Remember that memory use is roughly the limit multiplied by the row size, per open cursor and per session. Many concurrent sessions each holding large batches add up.
Pass the limit as a variable or constant rather than a literal. Then you can tune it in one place.
DECLARE
c_batch_size CONSTANT PLS_INTEGER := 500;
CURSOR c_emp IS
SELECT employee_id, salary FROM employees;
TYPE t_emp_tab IS TABLE OF c_emp%ROWTYPE;
l_emps t_emp_tab;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp BULK COLLECT INTO l_emps LIMIT c_batch_size;
EXIT WHEN l_emps.COUNT = 0;
DBMS_OUTPUT.PUT_LINE('Batch of ' || l_emps.COUNT || ' rows');
END LOOP;
CLOSE c_emp;
END;
/Collection types you can fetch into
You can bulk collect into a collection of records, as in the examples above. You can also fetch each column into its own collection.
DECLARE
TYPE t_id_tab IS TABLE OF employees.employee_id%TYPE;
TYPE t_sal_tab IS TABLE OF employees.salary%TYPE;
l_ids t_id_tab;
l_sals t_sal_tab;
CURSOR c_emp IS
SELECT employee_id, salary FROM employees WHERE department_id = 50;
BEGIN
OPEN c_emp;
FETCH c_emp BULK COLLECT INTO l_ids, l_sals LIMIT 1000;
CLOSE c_emp;
DBMS_OUTPUT.PUT_LINE(l_ids.COUNT || ' rows, first id ' || l_ids(1));
END;
/Parallel collections like this work, but a single collection of records keeps each row's values together and is easier to maintain. Oracle supports nested tables, associative arrays indexed by PLS_INTEGER, and VARRAYs as targets. Note that a VARRAY has a fixed maximum size. If a fetch returns more rows than the maximum, Oracle raises an error. Nested tables are the simplest choice.
Pairing BULK COLLECT with FORALL
Fetching in bulk removes the context switches on the read side. FORALL does the same for DML. It sends a whole collection to the SQL engine as one statement execution. The two work well together when you must transform rows in PL/SQL and then write them back.
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50;
TYPE t_id_tab IS TABLE OF employees.employee_id%TYPE;
TYPE t_sal_tab IS TABLE OF employees.salary%TYPE;
l_ids t_id_tab;
l_sals t_sal_tab;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp BULK COLLECT INTO l_ids, l_sals LIMIT 100;
EXIT WHEN l_ids.COUNT = 0;
FOR i IN 1 .. l_sals.COUNT LOOP
l_sals(i) := l_sals(i) * 1.05;
END LOOP;
FORALL i IN 1 .. l_ids.COUNT
UPDATE employees
SET salary = l_sals(i)
WHERE employee_id = l_ids(i);
DBMS_OUTPUT.PUT_LINE('Updated ' || SQL%ROWCOUNT || ' rows in this batch');
END LOOP;
CLOSE c_emp;
COMMIT;
END;
/In this example, SQL%ROWCOUNT after a FORALL gives the total rows affected by the whole statement. Use SQL%BULK_ROWCOUNT(i) to see the count for each individual element.
FORALL is a separate topic with its own error handling (SAVE EXCEPTIONS). Here it appears only to show where LIMIT fits in a larger job.
Edge cases and errors
- Calling
LIMIToutside aFETCH.LIMITis valid only in aFETCH ... BULK COLLECT INTOstatement. Using it inSELECT ... BULK COLLECT INTOis a compile error. - A limit of zero or less. A
LIMITthat evaluates to 0 or a negative number raises an error at run time. Validate any computed value. - Rows with
NULLcolumns. Nulls are stored in the collection as normal. Individual elements may be null, but the collection is not sparse. - Closing the cursor. Always close an explicit cursor after the loop. If an exception interrupts the loop, close it in the exception handler, testing
%ISOPENfirst. - Committing inside the fetch loop. Committing while a cursor is open is allowed for ordinary queries, but it can lead to
ORA-01555: snapshot too old, because the cursor needs a consistent view of the data from when it was opened. WithFOR UPDATE, a commit also releases the locks and invalidates the cursor, so fetching afterwards raisesORA-01002: fetch out of sequence. Commit after the loop where you can. - Modifying the collection between fetches. Each fetch overwrites the collection. Copy out anything you need to keep.
Comparing the approaches
| Technique | Rows in memory | Context switches | Best for |
|---|---|---|---|
| Plain `FETCH ... INTO` loop | 1 | One per row | Small result sets, simple logic |
| Cursor FOR loop | 1 (or 100 if auto-optimized) | One per row, or fewer if optimized | Readable row-by-row work without DML per row |
| `SELECT ... BULK COLLECT INTO` | All | One | Small, known-size result sets |
| `FETCH ... BULK COLLECT ... LIMIT` | Up to the limit | One per batch | Large result sets, bulk transformation |
If a single SQL statement can do the job, such as one UPDATE with a WHERE clause, it beats every cursor technique. Reach for BULK COLLECT ... LIMIT when PL/SQL logic must run between the read and the write.
Exercise
A table has 250 rows. You fetch with LIMIT 100 and write EXIT WHEN c_emp%NOTFOUND; immediately after each FETCH ... BULK COLLECT, before processing the collection. How many rows are processed, and why? What change fixes it?
Show answer
Only 200 rows are processed. The third fetch returns 50 rows, which is fewer than the limit, so Oracle sets %NOTFOUND to true and the loop exits before those 50 rows are processed. Fix it by exiting on l_emps.COUNT = 0 right after the fetch (so the partial batch is processed first), or by processing the batch and moving the EXIT WHEN c_emp%NOTFOUND to the end of the loop body.
Exercise
Why can SELECT last_name BULK COLLECT INTO l_names FROM employees be risky on a very large table, and which construct limits the risk?
Show answer
It loads every matching row into the session's memory at once, which can exhaust memory or slow the server. Opening an explicit cursor and using FETCH ... BULK COLLECT INTO ... LIMIT n in a loop keeps memory bounded to n rows at a time.