Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A Java service calls a PL/SQL function row by row in a loop for 500,000 records, and the job takes hours. What are the costs involved and how do you speed it up?

Each of the 500,000 calls pays a network round trip, a statement execution and a switch between the SQL and PL/SQL engines, and often a commit, so even 10 ms per row adds up to well over an hour. We speed it up by sending work in bulk: JDBC batching with addBatch and executeBatch, or passing arrays to a procedure that uses BULK COLLECT and FORALL. Best of all, we express the logic as one set-based statement such as INSERT ... SELECT or MERGE. We also raise the JDBC fetch size from Oracle's default of 10 rows and commit in batches of thousands.

Why this question is asked

Row-by-row processing, sometimes called slow-by-slow, is one of the most common causes of batch jobs that take hours instead of minutes. It is easy to write, because a loop that calls a function for each record is how we think about the problem in Java. Interviewers ask this to see whether we can break down where the time goes and choose a fix that matches the cost. In this answer, we will start with the slow loop, measure where the time goes, and then go through the fixes in order of effort: fetch size, batching, bulk PL/SQL, set-based SQL, and commit frequency.

1The Slow Loop

Here is the kind of code we usually find. The job reads records, calls a PL/SQL function for each one to compute a price, and writes the result.

Java
try (PreparedStatement read = conn.prepareStatement("SELECT id, sku, qty FROM order_lines WHERE batch_id = ?");
CallableStatement price = conn.prepareCall("{? = call pricing.line_price(?, ?)}");
PreparedStatement write = conn.prepareStatement("UPDATE order_lines SET price = ? WHERE id = ?")) {
read.setLong(1, batchId);
ResultSet rs = read.executeQuery(); // fetches 10 rows per round trip by default
while (rs.next()) {
price.registerOutParameter(1, Types.NUMERIC);
price.setString(2, rs.getString("sku"));
price.setInt(3, rs.getInt("qty"));
price.execute(); // round trip 1
write.setBigDecimal(1, price.getBigDecimal(1));
write.setLong(2, rs.getLong("id"));
write.executeUpdate(); // round trip 2
conn.commit(); // round trip 3, and a wait for the redo log write
}
}

2Where the Time Goes

Each row costs several separate things. First, network round trips: the function call, the update and the commit each travel to the database and back. Even inside one data centre that is about 0.3 to 1 ms each. Second, the context switch: every time SQL calls PL/SQL or PL/SQL runs SQL, Oracle switches between its two engines, and the function probably runs its own queries inside. Third, the commit: each commit waits until the redo log is written to disk, the 'log file sync' wait, typically 1 to 5 ms. Fourth, fetching: with the Oracle driver's default fetch size of 10, reading 500,000 rows takes 50,000 round trips just for the SELECT.

Add it up. If one row costs 3 round trips at 1 ms, a 2 ms commit and 5 ms for the function's own work, that is 10 ms per row. 500,000 rows x 10 ms = 5,000 seconds, almost an hour and a half, and on a slower network or a busier database it easily reaches several hours. Notice that almost none of this is real computation; it is waiting.

Cost per row in the slow loop (example)
StepPer rowFor 500,000 rows
Fetch (10 rows per trip)0.1 ms50 seconds
Function call round trip1 ms8 minutes
Function work and context switches5 ms42 minutes
Update round trip1 ms8 minutes
Commit (log file sync)2 ms17 minutes
Most of the time is waiting for round trips and commits, not computing.

3Quick Wins: Fetch Size, Batching and Batch Commits

The cheapest changes keep the structure but cut the round trips. We raise the fetch size so each trip brings 1,000 rows, we batch the updates, and we commit every 5,000 rows instead of every row.

Java
read.setFetchSize(1000); // 500 fetch round trips instead of 50,000
int n = 0;
while (rs.next()) {
BigDecimal p = computePrice(rs); // still one function call per row
write.setBigDecimal(1, p);
write.setLong(2, rs.getLong("id"));
write.addBatch();
if (++n % 5000 == 0) {
write.executeBatch(); // one round trip for 5,000 updates
conn.commit(); // 100 commits instead of 500,000
}
}
write.executeBatch();
conn.commit();

This alone often removes half or more of the time. The per-row function call remains, though. To remove that too we need to move the loop into the database or remove the loop entirely.

A word on commit size: committing every row is slow, but one commit at the end of 500,000 updates holds locks for the whole run and needs a lot of undo. Batches of a few thousand rows keep both manageable. If the job can fail halfway, it must also be restartable, for example by marking processed rows so a rerun skips them.

4Bulk PL/SQL: BULK COLLECT and FORALL

If the pricing logic must stay in PL/SQL, we can call one procedure for the whole batch and let it work in bulk inside the database. BULK COLLECT reads many rows into a collection, an in-memory array, with one context switch. FORALL sends a whole collection of DML to the SQL engine in one switch.

SQL
CREATE OR REPLACE PROCEDURE price_batch(p_batch_id IN NUMBER) IS
TYPE t_ids IS TABLE OF order_lines.id%TYPE;
TYPE t_prices IS TABLE OF order_lines.price%TYPE;
v_ids t_ids; v_prices t_prices;
CURSOR c IS SELECT id, pricing.line_price(sku, qty) FROM order_lines WHERE batch_id = p_batch_id;
BEGIN
OPEN c;
LOOP
FETCH c BULK COLLECT INTO v_ids, v_prices LIMIT 5000;
EXIT WHEN v_ids.COUNT = 0;
FORALL i IN 1 .. v_ids.COUNT
UPDATE order_lines SET price = v_prices(i) WHERE id = v_ids(i);
END LOOP;
CLOSE c;
END;
/
-- Java makes one call: {call price_batch(?)}

Java can also pass arrays into a procedure as Oracle collection types, using the Oracle driver's array support (for example OracleConnection.createOracleArray); check your driver version for the exact API. Either way, 500,000 network round trips become a handful. Note that this example commits from Java after the call, and for very large batches we would loop over batch ids from Java and commit after each.

5The Best Fix: One Set-Based Statement

Often the function is simple enough to express in SQL: a price lookup, a discount by quantity band, a currency conversion. Then the whole job becomes one statement that the database can run with its full set of optimisations, including parallel execution.

Java
MERGE INTO order_lines ol
USING (
SELECT l.id,
p.list_price * l.qty * (1 - NVL(d.discount_pct, 0) / 100) AS price
FROM order_lines l
JOIN prices p ON p.sku = l.sku
LEFT JOIN discounts d ON d.sku = l.sku AND l.qty BETWEEN d.min_qty AND d.max_qty
WHERE l.batch_id = :batch_id
) src
ON (ol.id = src.id)
WHEN MATCHED THEN UPDATE SET ol.price = src.price;
-- 500000 rows merged, in seconds to a few minutes

The reason this is so much faster is that the database reads each table once, joins them with hash joins, and writes in bulk, instead of performing 500,000 separate lookups. When we cannot do it all in one statement, a common compromise is to move the expensive part into SQL and leave only a small amount of logic in a bulk procedure.

6Follow-up questions

How would you find out where the time really goes before changing code?

I would trace one run. On the Java side, timings around each call; on the Oracle side, a session trace or an AWR or ASH report for the job's window (which needs the Diagnostics Pack licence), showing top waits such as 'SQL*Net message from client', which means round trips, and 'log file sync', which means commits.

Why can't Oracle cache the function result to make it faster?

It can in some cases: PL/SQL function result caching or a scalar subquery cache can avoid repeating calls with the same inputs. That helps when many rows share the same sku and qty, but it does not remove the network round trips of a row-by-row loop, so it is a complement, not a fix.

Is JDBC batching enough on its own?

For pure inserts and updates it often is, bringing hours down to minutes. But if each row still needs a separate function call to compute its value, those round trips remain, so the function work has to move into SQL or a bulk procedure as well.

7Conclusion

In this answer, we saw that a row-by-row job pays per row for network round trips, SQL to PL/SQL context switches, commits and small fetches, which turns 500,000 rows into hours of waiting. We cut the cost in steps: a larger fetch size, JDBC batching and batch commits; a bulk procedure using BULK COLLECT and FORALL or array parameters; and, best of all, one set-based INSERT ... SELECT or MERGE that lets the database do the work in a single pass.

What to say in the interviewAbout 90 seconds aloud

Open with

The time is almost all overhead, not computation. For each of the 500,000 rows the service makes a network round trip to call the function, Oracle switches between the SQL and PL/SQL engines, the function probably runs its own queries, then there is another round trip for the update and often a commit that waits on the redo log write.

Then, if they want more

The read side also fetches only 10 rows per round trip by default with the Oracle driver. At even 10 milliseconds per row that is about an hour and a half. I would fix it in steps.

First the cheap ones: set the fetch size to around 1,000, batch the writes with addBatch and executeBatch, and commit every few thousand rows instead of every row, while making the job restartable. That usually halves the time or better.

Then I would remove the per-row calls: either a single procedure that uses BULK COLLECT with a LIMIT and FORALL inside the database, or passing arrays of inputs to it.

The best option, if the logic allows, is to rewrite it as one set-based statement, a MERGE or INSERT SELECT joining prices and discounts, so the database reads each table once and the job takes minutes. Before changing anything I would trace one run to confirm whether round trips or commits dominate.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Java service calls a PL/SQL function row by row in a loop for 500,000 records, and the...": https://scrivio-interview-library.netlify.app/databases/oracle-and-sql-server/f276869b2e/