Sub topic 15
When a Loop Should Be a Single SQL Statement
This chapter assumes you can write the loop forms from earlier chapters (basic, WHILE, numeric FOR, cursor FOR) and use CASE and IF. It also assumes you know basic SQL DML and have the Oracle HR sample schema available. Its subject is a common performance mistake: using a PL/SQL loop to do work that one SQL statement can do.
Why a loop around SQL costs more
PL/SQL and SQL run in two separate engines inside the database. Each time a PL/SQL block runs a SQL statement, control passes from the PL/SQL engine to the SQL engine and back. This hand-off is called a context switch. One switch is cheap. A hundred thousand of them are not.
A loop that runs one UPDATE or INSERT per iteration also makes the SQL engine parse, bind, and execute the statement once per row. The optimizer plans each statement alone, so it can't choose a join method or a parallel plan for the whole job. Developers call this pattern "row-by-row" processing, or "slow-by-slow".
Recognizing the pattern
The typical form is a cursor FOR loop whose body runs DML keyed on the row just read:
BEGIN
FOR r IN (SELECT employee_id
FROM employees
WHERE department_id = 50) LOOP
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = r.employee_id;
END LOOP;
COMMIT;
END;
/The loop reads the rows with one query, then runs a separate UPDATE for each one. The WHERE clause of the query can go straight into the UPDATE:
BEGIN
UPDATE employees
SET salary = salary * 1.10
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
COMMIT;
END;
/SQL%ROWCOUNT still tells you how many rows changed, so you lose no information. The single statement is also shorter and easier to read.
Moving IF and CASE logic into SQL
Loops often stay because the body contains an IF or CASE that picks a different action per row. In most cases that logic can move into the statement. The SQL CASE expression, covered earlier in this tutorial, returns a value, so it can appear in SET, SELECT, and WHERE clauses.
This loop applies a tiered raise:
BEGIN
FOR r IN (SELECT employee_id, salary
FROM employees
WHERE department_id = 50) LOOP
IF r.salary < 3000 THEN
UPDATE employees SET salary = salary * 1.15
WHERE employee_id = r.employee_id;
ELSIF r.salary < 6000 THEN
UPDATE employees SET salary = salary * 1.10
WHERE employee_id = r.employee_id;
ELSE
UPDATE employees SET salary = salary * 1.05
WHERE employee_id = r.employee_id;
END IF;
END LOOP;
END;
/The equivalent single statement:
BEGIN
UPDATE employees
SET salary = CASE
WHEN salary < 3000 THEN salary * 1.15
WHEN salary < 6000 THEN salary * 1.10
ELSE salary * 1.05
END
WHERE department_id = 50;
END;
/Only the CASE expression works inside SQL. The CASE statement, which ends in END CASE, and the IF statement are PL/SQL constructs and are not valid in a SQL statement.
Other set-based replacements
| Loop pattern | Single-statement replacement |
|---|---|
| Query rows, then `INSERT` each into another table | `INSERT INTO target SELECT ... FROM source` |
| Query rows, then `UPDATE` each using values from another table | `MERGE`, or `UPDATE` with a correlated subquery |
| Query rows, then `INSERT` if missing or `UPDATE` if present | `MERGE INTO target USING source ON (...)` |
| Query rows, then `DELETE` each | `DELETE ... WHERE` with the same condition |
| Loop that adds a running total or counter | Aggregate or analytic function (`SUM`, `SUM(...) OVER (...)`) |
Here is an upsert loop replaced by MERGE. The example assumes a salary_history table you have created:
BEGIN
MERGE INTO salary_history h
USING (SELECT employee_id, salary FROM employees) e
ON (h.employee_id = e.employee_id)
WHEN MATCHED THEN
UPDATE SET h.salary = e.salary
WHEN NOT MATCHED THEN
INSERT (employee_id, salary)
VALUES (e.employee_id, e.salary);
END;
/Measuring the difference
Run this on a scratch schema to compare the two approaches on your own system. DBMS_UTILITY.GET_TIME returns hundredths of a second. The absolute numbers depend on your hardware and settings, but the single statement is usually many times faster.
CREATE TABLE demo_rows (id NUMBER, val VARCHAR2(20));
DECLARE
l_start PLS_INTEGER;
BEGIN
l_start := DBMS_UTILITY.GET_TIME;
FOR i IN 1..100000 LOOP
INSERT INTO demo_rows VALUES (i, 'row ' || i);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Loop: ' || (DBMS_UTILITY.GET_TIME - l_start) || ' cs');
ROLLBACK;
l_start := DBMS_UTILITY.GET_TIME;
INSERT INTO demo_rows
SELECT LEVEL, 'row ' || LEVEL FROM dual CONNECT BY LEVEL <= 100000;
DBMS_OUTPUT.PUT_LINE('Single: ' || (DBMS_UTILITY.GET_TIME - l_start) || ' cs');
ROLLBACK;
END;
/
DROP TABLE demo_rows;When the logic cannot be one statement
Sometimes each row needs real procedural work. Examples are calling a package procedure, applying rules too complex for CASE, or writing a log entry per row. You then have two options.
First, keep the loop but batch the SQL. BULK COLLECT fetches many rows into a collection in one engine switch, and FORALL sends a whole collection of DML to the SQL engine in one switch:
DECLARE
TYPE t_ids IS TABLE OF employees.employee_id%TYPE;
l_ids t_ids;
BEGIN
SELECT employee_id
BULK COLLECT INTO l_ids
FROM employees
WHERE department_id = 50;
IF l_ids.COUNT > 0 THEN
FORALL i IN 1..l_ids.COUNT
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = l_ids(i);
END IF;
END;
/FORALL is not a loop. It is a single DML statement that is bound to every element of the collection. Its body must be exactly one DML statement, and you can't put an IF or EXIT inside it. The IF l_ids.COUNT > 0 guard avoids running it on an empty collection.
Second, if the loop only reads rows and does work in PL/SQL, a plain cursor FOR loop is often fine. With the default PLSQL_OPTIMIZE_LEVEL of 2, the compiler fetches 100 rows per round trip behind the scenes. The cost comes from running DML inside the loop, not from the loop itself.
Edge cases to watch
- Error handling per row. A row-by-row loop lets you catch an exception for one bad row and continue. A single statement fails as a whole and rolls back its own changes. If you need to keep the good rows, add a
LOG ERRORS INTOclause. Create the error table first withDBMS_ERRLOG.CREATE_ERROR_LOG. ForFORALL, useSAVE EXCEPTIONS. - Commits inside the loop. Committing every N rows seems to reduce undo use, but it breaks atomicity. If the job fails halfway, you have a partly changed table and no easy restart point. It can also cause ORA-01555 ("snapshot too old") when the loop is still reading from a query. Commit once at the end unless you have a measured reason not to.
- Dependencies between rows. If row N's result depends on row N-1's, a loop may be needed. Even then, try analytic functions such as
LAGorSUM ... OVERfirst. - Side effects. If the per-row work sends email or calls an external system, it can't be set-based. Keep the loop and limit the SQL inside it.
- Small data. Looping over 20 rows costs nothing noticeable. Clarity should decide. Rewrite when the row count is large or growing.
Choosing between the options
| Situation | Best choice |
|---|---|
| Row selection and change both expressible in SQL | One `INSERT`, `UPDATE`, `DELETE`, or `MERGE` |
| Per-row choice between a few values | SQL `CASE` expression inside the statement |
| Per-row procedural logic, then DML | `BULK COLLECT` plus `FORALL` |
| Read-only processing in PL/SQL | Cursor FOR loop |
| Side effects on each row, such as calling external code | Loop, with the SQL kept minimal |
Exercise
The block below gives a 5% raise to every employee in department 80 whose salary is under 10000. Rewrite it as one SQL statement, and name the PL/SQL attribute you can use afterwards to report how many rows changed. BEGIN FOR r IN (SELECT employeeid FROM employees WHERE departmentid = 80 AND salary < 10000) LOOP UPDATE employees SET salary = salary * 1.05 WHERE employeeid = r.employeeid; END LOOP; END;
Show answer
UPDATE employees SET salary = salary * 1.05 WHERE department_id = 80 AND salary < 10000; The attribute is SQL%ROWCOUNT, which holds the number of rows affected by the most recent DML statement. The query's conditions move directly into the UPDATE's WHERE clause, so the loop and its per-row context switches disappear.
Exercise
A loop calls a PL/SQL function calc_bonus(employee_id) for each employee and updates a bonus column with the result. The function contains rules that cannot be written in SQL. Which technique reduces context switches while keeping the function call, and why can't you put an IF statement inside the FORALL body?
Show answer
Use BULK COLLECT to fetch the IDs (and computed bonuses) into collections, then FORALL to apply all the updates in one hand-off to the SQL engine. The function still runs in PL/SQL, so compute the bonuses in a regular loop over the collection and store them in a second collection before the FORALL. FORALL is a single DML statement bound to every collection element, not a loop, so its body must be exactly one DML statement and cannot hold IF or other PL/SQL statements.