Video in progress

You need to insert 10,000 rows through JDBC. How do separate `executeUpdate` calls, a batch, and a multi-row `INSERT` differ?

With separate inserts there is one network round trip per row, so it's the slowest. addBatch/executeBatch collects the statements and sends them together, and in PgJDBC reWriteBatchedInserts=true turns them into a multi-row INSERT, which speeds things up further.

📖 Answer

Even with just 0.5 ms of network latency to the database, 10,000 separate queries spend 5 seconds on waiting alone. And if autocommit is on, every row is its own commit, each with a WAL flush to disk.

The batch version:

String sql = "INSERT INTO product (sku, name, price) VALUES (?, ?, ?)";
try (Connection con = ds.getConnection();
     PreparedStatement ps = con.prepareStatement(sql)) {
    con.setAutoCommit(false);
    int n = 0;
    for (Product p : products) {
        ps.setString(1, p.sku());
        ps.setString(2, p.name());
        ps.setBigDecimal(3, p.price());
        ps.addBatch();
        if (++n % 1000 == 0) ps.executeBatch();   // so we don't fill up memory
    }
    ps.executeBatch();
    con.commit();
}

If you add reWriteBatchedInserts=true to the URL, the driver combines several inserts into the form INSERT ... VALUES (...), (...), (...), which in PostgreSQL is several times faster again.

If you use Hibernate, you need to enable hibernate.jdbc.batch_size, but with GenerationType.IDENTITY batch inserts get disabled. For a very large volume (millions of rows), COPY is the fastest way.