G-3210: Always use BULK OPERATIONS (BULK COLLECT, FORALL) whenever you have to execute a DML statement for more than 4 times.
Major
Efficiency
Reason
Context switches between PL/SQL and SQL are extremely costly. BULK Operations reduce the number of switches by passing an array to the SQL engine, which is used to execute the given statements repeatedly.
(Depending on the PLSQL_OPTIMIZE_LEVEL parameter a conversion to BULK COLLECT will be done by the PL/SQL compiler automatically.)
Example (bad)
DECLARE
t_employee_ids employee_api.t_employee_ids_type;
co_increase CONSTANT employees.salary%type := 0.1;
co_department_id CONSTANT departments.department_id%TYPE := 10;
BEGIN
t_employee_ids := employee_api.employee_ids_by_department(
id_in => co_department_id
);
<<process_employees>>
FOR i IN 1..t_employee_ids.COUNT()
LOOP
UPDATE employees
SET salary = salary + (salary * co_increase)
WHERE employee_id = t_employee_ids(i);
END LOOP process_employees;
END;
/
Example (good)
DECLARE
t_employee_ids employee_api.t_employee_ids_type;
co_increase CONSTANT employees.salary%type := 0.1;
co_department_id CONSTANT departments.department_id%TYPE := 10;
BEGIN
t_employee_ids := employee_api.employee_ids_by_department(
id_in => co_department_id
);
<<process_employees>>
FORALL i IN 1..t_employee_ids.COUNT()
UPDATE employees
SET salary = salary + (salary * co_increase)
WHERE employee_id = t_employee_ids(i);
END;
/