When standard PL/SQL executes a loop containing SQL statements, execution repeatedly switches between two distinct runtime engines: the PL/SQL Engine and the SQL Engine. This mechanism, known as Context Switching, is the primary reason why iterative loops over large datasets run sluggishly.
POOR DESIGN (Context Switch per row):
PL/SQL Loop ──(Context Switch)──> SQL Engine (UPDATE 1 row)
PL/SQL Loop <──(Return result)─── SQL Engine
PL/SQL Loop ──(Context Switch)──> SQL Engine (UPDATE 1 row)
(Repeated 100,000 times = severe CPU latency)
ENTERPRISE DESIGN (Bulk Operations):
PL/SQL Engine ──(One Context Switch with 5,000 rows)──> SQL Engine (Batch UPDATE)
BULK COLLECT with LIMIT
Instead of fetching one row per iteration into scalar variables, BULK COLLECT reads batches of rows directly into collections in memory:
DECLARE
-- Define a collection type of customer records
TYPE t_customers IS TABLE OF customers%ROWTYPE;
v_batch t_customers;
CURSOR c_vip IS
SELECT * FROM customers WHERE lifetime_value > 50000;
BEGIN
OPEN c_vip;
LOOP
-- Batch fetch 2,500 rows at a time to prevent PGA memory exhaustion
FETCH c_vip BULK COLLECT INTO v_batch LIMIT 2500;
EXIT WHEN v_batch.COUNT = 0;
-- Process the batch in memory
DBMS_OUTPUT.PUT_LINE('Fetched batch of ' || v_batch.COUNT || ' VIP customers.');
END LOOP;
CLOSE c_vip;
END;
/
The FORALL Statement
FORALL is not a standard loop: it is a directive telling the PL/SQL compiler to bundle an entire collection of parameters and execute a single batch DML statement in the SQL engine:
CREATE OR REPLACE PROCEDURE bulk_update_credit_scores (
p_account_ids IN sys.odcinumberlist,
p_score_deltas IN sys.odcinumberlist
) IS
BEGIN
-- Executes all updates in a single engine context switch!
FORALL i IN 1..p_account_ids.COUNT
UPDATE accounts
SET credit_score = LEAST(850, GREATEST(300, credit_score + p_score_deltas(i))),
score_updated_at = SYSDATE
WHERE account_id = p_account_ids(i);
COMMIT;
END;
/
Handling Exceptions in Bulk: SAVE EXCEPTIONS
In standard processing, if row 42 out of 5,000 raises an error (such as a check constraint violation), the entire transaction aborts. Using SAVE EXCEPTIONS allows the batch to proceed, recording all individual row errors into SQL%BULK_EXCEPTIONS:
DECLARE
TYPE t_salaries IS TABLE OF employees.salary%TYPE;
TYPE t_emp_ids IS TABLE OF employees.employee_id%TYPE;
v_ids t_emp_ids := t_emp_ids(101, 102, 103, 104);
v_sals t_salaries := t_salaries(75000, -10, 85000, 92000); -- -10 violates CHECK constraint
bulk_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(bulk_errors, -24381); -- ORA-24381: error(s) in array DML
BEGIN
FORALL i IN 1..v_ids.COUNT SAVE EXCEPTIONS
UPDATE employees SET salary = v_sals(i) WHERE employee_id = v_ids(i);
EXCEPTION
WHEN bulk_errors THEN
FOR j IN 1..SQL%BULK_EXCEPTION_COUNT LOOP
DBMS_OUTPUT.PUT_LINE(
'Row index ' || SQL%BULK_EXCEPTIONS(j).ERROR_INDEX ||
' failed with code ORA-' || SQL%BULK_EXCEPTIONS(j).ERROR_CODE
);
END LOOP;
-- Valid rows were updated; handle logging or rollback here
END;
/
Exercises
- Refactor a row-by-row cursor loop updating order shipping statuses into a performant
BULK COLLECT ... LIMIT 5000andFORALLpipeline. - Explain the risk of running
BULK COLLECT INTOwithout aLIMITclause on a table with 20 million rows. - Write a procedure using
SAVE EXCEPTIONSthat logs failed row IDs to an error table while committing the successful updates.