Skip to content

Batching Inserts by Combining Queries

Obligatory warning: Always escape your inputs! This assumes you are migrating known safe data!

I see lots of legacy code (especially bulk data migrations) that perform database operations inside a loop. Like this:

This results in a series of queries:

but we can do better. SQL inserts can be stacked into one query:

This still inserts all 3 records, in just one transaction. And it’s easy to retrofit our existing code:

A little more code of course, but this will speed up your inserts dramatically.