Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Inserting 1 million rows with a JDBC loop of executeUpdate takes 40 minutes against PostgreSQL. Show how you would make it fast with JDBC.

The loop is slow because each executeUpdate is a separate network round trip and, with autocommit on, a separate commit that waits for a WAL flush to disk. We make it fast by turning autocommit off, sending rows with addBatch and executeBatch in chunks of about 1,000, committing per chunk or at the end, and adding reWriteBatchedInserts=true to the pgjdbc URL so batches become multi-row inserts. For the fastest load we use COPY through the driver's CopyManager; on MySQL the equivalents are rewriteBatchedStatements=true and LOAD DATA.

Why this question is asked

Loading a large amount of data with a simple loop is something almost every developer does once, and 40 minutes for a million rows is a typical result. Interviewers ask it because the fix requires understanding where the time actually goes, the network and the commit, rather than blaming the database. In this answer, we will measure where the time goes in the loop, fix it with batching, let the driver rewrite the batches, use COPY for the fastest path, mention MySQL, and look at what COPY gives up.

1Where the Time Goes in the Loop

Here is the slow version. Nothing in it looks wrong, which is why it is so common.

Java
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO items (id, name, price) VALUES (?, ?, ?)")) {
for (Item it : items) { // 1,000,000 items, autocommit on
ps.setLong(1, it.id());
ps.setString(2, it.name());
ps.setBigDecimal(3, it.price());
ps.executeUpdate(); // one round trip and one commit per row
}
}
// about 40 minutes: roughly 2.4 ms per row

Each executeUpdate sends the statement to the server and waits for the reply, a network round trip of perhaps half a millisecond to a millisecond even inside a data centre. With autocommit on, which is the JDBC default, every statement is also its own transaction. At commit, PostgreSQL must make sure the commit record of the write-ahead log, the WAL, is flushed to disk with fsync before replying, and a flush typically costs around a millisecond. The insert itself is a small fraction of that. So almost all of the 40 minutes is waiting: a million times for the network and a million times for the disk.

2Fix 1: Batch the Statements and Commit Less Often

JDBC batching lets us queue many parameter sets and send them together. Turning autocommit off lets us commit once per chunk instead of once per row.

Java
conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO items (id, name, price) VALUES (?, ?, ?)")) {
int n = 0;
for (Item it : items) {
ps.setLong(1, it.id());
ps.setString(2, it.name());
ps.setBigDecimal(3, it.price());
ps.addBatch(); // queued in the driver, nothing sent yet
if (++n % 1_000 == 0) {
ps.executeBatch(); // 1,000 rows in one exchange
conn.commit(); // one WAL flush per 1,000 rows
}
}
ps.executeBatch(); // the remainder
conn.commit();
}
// about 1 to 2 minutes (illustrative)

Notice the two separate gains. Batching cuts round trips from a million to a thousand, and the commit per chunk cuts WAL flushes the same way. Chunks of about 1,000 rows keep memory in the driver small and keep each transaction short; committing per chunk also means that if row 700,000 fails, the first 699 chunks are kept, so the loader should be able to restart from the last committed chunk. If the load must be all or nothing, we commit once at the end instead.

3Fix 2: Let pgjdbc Rewrite Batches

By default pgjdbc sends a batch as many individual INSERT executions pipelined together. With reWriteBatchedInserts=true in the connection URL, it rewrites them into multi-row inserts, INSERT INTO items VALUES (...), (...), (...), so the server parses and executes far fewer statements.

Java
jdbc:postgresql://db:5432/shop?reWriteBatchedInserts=true
// same Java code as Fix 1
// about 20 to 30 seconds (illustrative)

One side effect: with the rewrite, executeBatch may report the update counts differently, often as SUCCESS_NO_INFO instead of 1 per row, so code that checks each count should not rely on exact values. MySQL's Connector/J has the equivalent setting rewriteBatchedStatements=true; without it, MySQL batches gain much less.

4Fix 3: COPY for the Fastest Load

PostgreSQL's COPY command is built for bulk loading: the client streams rows in a simple text or CSV format, and the server inserts them without per-statement overhead. pgjdbc exposes it through CopyManager.

Java
CopyManager copy = conn.unwrap(PGConnection.class).getCopyAPI();
long rows = copy.copyIn(
"COPY items (id, name, price) FROM STDIN WITH (FORMAT csv)",
csvReader); // a Reader producing lines like 42,"Blue mug",9.90
conn.commit();
System.out.println(rows); // 1000000
// about 5 to 10 seconds (illustrative)
A million rows, by method
MethodRound tripsCommitsTime (illustrative)
executeUpdate loop, autocommit1,000,0001,000,000about 40 min
addBatch, chunks of 1,000about 1,0001,0001 to 2 min
+ reWriteBatchedInserts=trueabout 1,0001,00020 to 30 s
COPY with CopyManagerone stream15 to 10 s
Times depend on hardware and network; the ratios are what matter.

The data must be correctly escaped CSV, so values containing commas, quotes or newlines need care; a CSV library or a writer that quotes every field avoids surprises. For MySQL, the bulk equivalent is LOAD DATA, or LOAD DATA LOCAL INFILE for a file on the client, which must be enabled on both client and server.

5Follow-up questions

What is lost when you choose COPY over batched inserts?

Several things. COPY does not support ON CONFLICT, so upserts need a load into a staging table followed by INSERT ... SELECT ... ON CONFLICT. It cannot return generated keys the way RETURNING or getGeneratedKeys can. One bad row aborts the whole COPY by default, so error handling is coarse, although PostgreSQL 17 added an ON_ERROR option that can skip rows with invalid data types; check your version. It is also a PostgreSQL-specific API, so the code is less portable than standard JDBC. Constraints and triggers still apply.

Why not make the batch 100,000 rows?

Gains flatten out after a few thousand rows, while the driver holds more data in memory, a failure throws away more work, and long transactions hold locks and delay vacuum. A chunk of 500 to 5,000 rows is usually the sweet spot; measure on your system.

Does Spring's JdbcTemplate support this?

Yes. jdbcTemplate.batchUpdate(sql, list, 1000, setter) sends the list in chunks of 1,000 with JDBC batching, and the reWriteBatchedInserts URL setting still applies. For COPY, we unwrap the connection to PGConnection inside a ConnectionCallback.

6Conclusion

In this answer, we saw that inserting row by row with autocommit is slow because each row costs a network round trip and a commit with a WAL flush. Batching with addBatch and executeBatch in chunks of about 1,000 rows, with autocommit off, removes most of that waiting, and reWriteBatchedInserts=true lets pgjdbc turn batches into multi-row inserts. COPY through CopyManager is the fastest path, at the cost of upserts, returned keys, per-row error handling and portability, and on MySQL the equivalents are rewriteBatchedStatements=true and LOAD DATA.

What to say in the interviewAbout 80 seconds aloud

Open with

The time is not in the inserts themselves, it is in waiting. Each executeUpdate is a network round trip, and with autocommit on each one is its own transaction, so the server has to flush the WAL to disk with fsync before acknowledging every single row.

Then, if they want more

A million round trips plus a million flushes is about forty minutes. First I turn autocommit off and use addBatch and executeBatch, sending chunks of about a thousand rows and committing per chunk, or once at the end if the load must be all or nothing. That cuts round trips and flushes by a factor of a thousand.

Then I add reWriteBatchedInserts=true to the pgjdbc URL, so the driver turns each batch into multi-row INSERT statements, which is usually another big gain. With JdbcTemplate that is just batchUpdate with a batch size. For the fastest load I would use COPY through the driver's CopyManager, streaming CSV with copyIn, which loads a million rows in seconds.

The trade-off is that COPY has no ON CONFLICT, no generated keys returned, coarse error handling where one bad row fails the load, and it is PostgreSQL-specific, so for upserts I copy into a staging table and insert from there. On MySQL the equivalents are rewriteBatchedStatements=true and LOAD DATA.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 17
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 "Inserting 1 million rows with a JDBC loop of executeUpdate takes 40 minutes against...": https://scrivio-interview-library.netlify.app/databases/query-optimization/80179bb51a/