Saturday, 22 March 2025

FORALL Command in Oracle PL/SQL

 The FORALL command in Oracle PL/SQL is a helpful feature designed to optimize bulk data manipulation. It enhances performance by minimizing context switches between the PL/SQL engine and the SQL engine, making it ideal for large-scale data operations.

What is the FORALL Command?

FORALL is a loop construct that efficiently performs bulk INSERT, UPDATE, or DELETE operations. Unlike traditional FOR loops, FORALL processes entire collections in a single batch, reducing the overhead of multiple context switches.

Syntax of FORALL

FORALL index IN lower_bound .. upper_bound
    sql_statement;

Examples of Using FORALL

DECLARE
    TYPE emp_data IS TABLE OF employees%ROWTYPE;
    v_emps emp_data;
BEGIN
    SELECT * BULK COLLECT INTO v_emps FROM employees_data WHERE department_id = 100;

    FORALL i IN v_emps.FIRST .. v_emps.LAST
        INSERT INTO employees_data_table VALUES v_emps(i);

    COMMIT;
END;
/

The FORALL command is a vital tool for enhancing performance in Oracle PL/SQL bulk operations. By mastering its syntax, combining it with SAVE EXCEPTIONS, and following best practices, you can significantly improve the efficiency of data manipulation tasks in your Oracle database projects.