You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
INSERT INTO my_table (my_num, my_str) VALUES
($1,$2)
,($3, $4)
,($5,$6)
... etc. depending on how many records you pass in
By the way, this project looks great!
Reacted by Andrew McHarg, Smit, Kirill Bulatov, Daniel García, jf908, Jonas Bushart, Sven-Hendrik Haase, Diego Stratta, Pavel Perestoronin, Ken Kaizu and 91 more
Reacted by Michael Sasser, Kyle L. Davis, musjj and dzmitry-lahoda
This seems a popular concern right now! I asked this question on Discord and the answer for now is this is not possible, unless you generate the query yourself (and lose a lot of the compile-time-safety features as a result).
There seems to be some activity in the area though:
@connec I missed those related topics! Thanks for pointing them out.
Yes, for me, this is the biggest need for interacting with SQL -- I can write SQL myself and make sure it is safe, and binding a few arguments isn't hard, but it's a pain to bind an arbitrary number of ($n, $n+1), ($n+2, $n+3), etc.!
I ran into a similar issue. I think I have a solution (for now), but it is somewhat hideous:
sqlx::query!(
"WITH
a AS (SELECT row_number() over(), * FROM UNNEST( $1::UUID[] ) as group_id),
b AS (SELECT row_number() over(), * FROM UNNEST( $2::UUID[] ) as variable_id),
c AS (SELECT row_number() over(), * FROM UNNEST( $3::INTEGER[] ) as ordering)
INSERT INTO groups
SELECT a.group_id, b.variable_id, c.ordering FROM a
JOIN b ON a.row_number = b.row_number
JOIN c ON a.row_number = c.row_number",
&group_id_arr,
&self.variable_ids,
&order_arr
).execute(&mut *conn).await?;
The "trick" is that you can pass in a Vector of items to be a Postgres ARRAY type, and UNNEST that array to turn it into a set of rows. So, above, I basically split the thing I want to insert into a vec for each column of values (fortunately only 3 for me), which each get turned into a temporary table with row numbers. Once I have these, I can join them all on the row numbers to produce a final table of values, which I then pass to the INSERT.
It's pretty hideous, and I'd love to find a more concise or better approach, but it's the best I have so far!
I need to actually test it properly next, to make sure it does what I am hoping it does..
Reacted by Scott Driggers, Stefan Crnojević, Arnau Orriols, Andras Slemmer and cognivore
As an aside, I also tried doing a simpler approach of passing a single array of all of the values I wanted to update at once, but I hit a wall where SQLx did not understand the type of the array I was trying to provide, so that's what led me to splitting the array up and recombining it in SQL instead.
Just a quick FYI that, at least from a postgres POV, this works as I'd like. Here's a brief example:
db=> create table foo (id integer, foo text, bar boolean);
CREATE TABLE
db=> WITH a AS (select row_number() over(), * from unnest(ARRAY[1,2,3]) as id), b AS (select row_number() over(), * from unnest(ARRAY['a','b','c']) as foo), c AS (select row_number() over(), * from unnest(ARRAY[true,false,true]) as bar) INSERT INTO foo SELECT a.id, b.foo, c.bar FROM a JOIN b ON a.row_number = b.row_number JOIN c ON a.row_number = c.row_number;
INSERT 0 3
db=> select * from foo;
id | foo | bar
----+-----+-----
1 | a | t
2 | b | f
3 | c | t
For Postgres, the below works, and is easy. Maybe this is good enough and nothing else is needed to support INSERTing multiple records, at least for Postgres.
let lala = vec![("abc", true), ("xyz", false)];
let mut v1: Vec<String> = Vec::new();
let mut v2: Vec<bool> = Vec::new();
lala.into_iter().for_each(|todo| {
v1.push(todo.0.into());
v2.push(todo.1);
});
dbg!((&v1, &v2));
let todo = sqlx::query(
r#"INSERT INTO foo (description, done)
SELECT description, done
FROM UNNEST($1, $2) as a(description, done)
RETURNING id, description, done"#,
)
.bind(&v1)
.bind(&v2)
.map(|row: PgRow| Todo {
id: row.get(0),
description: row.get(1),
done: row.get(2),
})
.fetch_one(&mut tx)
.await.map_err(|e| dbg!(e) )?;
Reacted by Mingwei Zhang, Joseph Krusling, Oak, Luis Roel, Garrison Hess, cheolgyu, Jakub Beránek and Kento Maruyama
Reacted by Joseph Krusling, berryjam and Garrison Hess
Until this is fully supported, you can send an entire json object/list of
records, in one insert command and then in the insert query break the json
into rows (in postgres, it is something like "jsonb_to_rows"). This is less
efficient than being able to do it directly (using binary communication
instead of json), but much much better than doing single inserts.
Is doing multiple single inserts that much inefficient?
For example consider a web app route POST /todos that let you insert 10 rows.
I understand that a post request will take longer to execute because now the request handler has to .await 10 times instead of just one time and other I/O operations can come in between those .awaits.
But the data the request handler has to send to postgres, isn't it almost same as above?
"Almost" because now there will be 10 headers, one for each row instead of 1 header for all 10 rows when we send data to postgres.
Comparing this with the overhead of doing the json conversion, wouldn't this be more efficient?
If the're on different servers that are "far apart" (in different datacenters) then the JSON solution is most likely faster, maybe substantially faster. If they're on the same machine then you're probably right and the JSON solution is slower, but not slow enough that you would notice outside of microbenchmarks. If it really matters, benchmark it for your specific situation.
I had trouble inserting array fields here because UNNEST on multi-dimensional arrays fully flattens the values (at least on postgres). I ended up switching from using UNNEST to doing a huge cross join and using generate_subscripts to pick out the right entries.
Here is the slightly simplified example.
INSERT INTO entries(
feed,
source_url,
categories,
source_body_html)
SELECT
($1::INT8[])[i],
NULLIF(($2::TEXT[])[i], ''),
COALESCE(
(SELECT ARRAY_AGG(e) FROM jsonb_array_elements_text(($6::JSONB[])[i]) as e),
ARRAY[]::TEXT[]),
($8::TEXT[])[i]
FROM generate_subscripts($1::INT8[], 1) AS i
RETURNING entries.id, entries.source_url
I've only really tested with <50 rows but there is no obvious slowdown occurring here. It seems to be fairly fast.
That being said this is an incredibly bad API:
Very error prone in ways that may pass the compiler checking.
Very inconvenient.
Very confusing to a reader.
Also requires contorting your data into columns before even getting to the query part.
I would love to see a good interface here. Ideally I could just insert an IntoIterator<Item: impl ToRow> or similar. Batching as needed could be handled automatically. It would be nice if this used the bulk-loading features of each DBMS but that may not be feasible because at least for postgres COPY doesn't allow returning anything.
Reacted by Alexander Tesfamichael, Pedro Souto and Nick Kocharhook
In case anyone finds it useful, query builder can also be used with ON DUPLICATE KEY UPDATE and RETURNING clauses (only works with MariaDB, not MySQL). EXPECTED_RECORDS is an array of structs and the column key is a unique key. I'm using this query to map a Rust enum to record IDs and ensure I only have one copy in the database (init step so there is no error handling).
letmut qb:QueryBuilder<MySql> = QueryBuilder::new("INSERT INTO event (key, success, description) ",);
qb.push_values(EXPECTED_RECORDS.iter(), |mut b, rec| {
b.push_bind(rec.key).push_bind(rec.success).push_bind(rec.description);});
qb.push("ON DUPLICATE KEY UPDATE success=VALUES(success), description=VALUES(description) RETURNING id",);letmut rows = qb.build().fetch(pool);letmut ret = BTreeMap::new();letmut count:usize = 0;whileletSome(row) = rows.try_next().await.unwrap(){// FIXME: it would be best to use `try_get("id")`, but this is currently broken// <https://github.com/launchbadge/sqlx/issues/1530>let id:u32 = row.try_get(0).unwrap();
ret.insert(EXPECTED_RECORDS[count].ty, id);
count += 1;}// sanity check that all rows were coveredassert_eq!(count,EXPECTED_RECORDS.len());
I think this is pretty clean, but maybe the checked macros could get some syntax to handle this too. Perhaps
let rows = sqlx::query!("INSERT INTO event (key, success description) VALUES -- This gets expanded to `(?, ?, ?)` for each item in iter repeat! { (key, success, description) } ON DUPLICATE KEY UPDATE success=VALUES(success), description=VALUES(description) RETURNING id",EXPECTED_RECORDS.iter()).fetch_all(pool).unwrap();for row in rows {println!("id: {id}");}
Reacted by Alexandre Macabies, szaldivar, Ray P, Gabriel Pureliani, Waldemar Lehner, Bèr Kessels, weidix, Mohammad Kermani and Jakub Beránek
For folks looking for a solution for sqlite (which doesn't have UNNEST), I compared the timing for three different approaches for a mass insert of 100k BLOB fields of 32 bytes each:
Generating a JSON array of hex strings and doing INSERT INTO the_table (blob_field) SELECT unhex(value) as blob_field from json_each(?), with various batch sizes
Using QueryBuilder to build a VALUES statement, with various batch sizes.
Inserting one by one using VALUES (?).
Here's the result:
Time for mass insert using JSON (batch size 100000): 204.063168ms
Time for mass insert using JSON (batch size 10000): 318.28208ms
Time for mass insert using JSON (batch size 1000): 785.099067ms
Time for mass insert using JSON (batch size 100): 3.351116507s
Time for mass insert using QueryBuilder (batch size 10000): 205.967325ms
Time for mass insert using QueryBuilder (batch size 1000): 734.117792ms
Time for mass insert using QueryBuilder (batch size 100): 3.353956729s
Time for mass insert one by one: 67.237277417s
QueryBuilder performs better, if you're within the limits of QueryBuilder. JSON isn't far behind, though, and doesn't have the same limits. (You're still limited by available memory, though.)
Reacted by Stephen Willcock, An Cao, Farseen, Qqwy / Marten, Unic, beef, cybotrade, Gabriel de Perthuis, Zach Paden, Onè and 6 more
@joshtriplett Thanks for taking the time to run this performance comparison! Do you happen to remember if that comparison was run inside a transaction or not? I'm guessing yes, since without transaction probably would have been much slower, right? No worries if you don't remember, you've already provided a lot of value either way
@Pascal-So I didn't try putting everything inside a single transaction; I just ran a separate query call for each INSERT INTO.
Here are some freshly collected numbers without a transaction:
Time for mass insert using JSON (batch size 100000): 236.457855ms
Time for mass insert using JSON (batch size 10000): 344.826149ms
Time for mass insert using JSON (batch size 1000): 1.108914844s
Time for mass insert using JSON (batch size 100): 3.79396493s
Time for mass insert using QueryBuilder (batch size 10000): 302.525221ms
Time for mass insert using QueryBuilder (batch size 1000): 976.944333ms
Time for mass insert using QueryBuilder (batch size 100): 3.427136517s
Time for mass insert one by one: 73.180062435s
And here are the numbers with a transaction:
Time for mass insert using JSON (batch size 100000): 195.76455ms
Time for mass insert using JSON (batch size 10000): 195.996502ms
Time for mass insert using JSON (batch size 1000): 269.762261ms
Time for mass insert using JSON (batch size 100): 372.181148ms
Time for mass insert using QueryBuilder (batch size 10000): 205.156455ms
Time for mass insert using QueryBuilder (batch size 1000): 308.282139ms
Time for mass insert using QueryBuilder (batch size 100): 460.519417ms
Time for mass insert one by one: 1.221496278s
Reacted by HookedBehemoth, Nick Kocharhook, Stefan Schindler, Victor Wanderley Barbosa, Rémi Bardon, Arto Bendiken, Jakub Beránek, Apollo314 and Valerio Viperino
For folks looking for a solution for sqlite (which doesn't have UNNEST), I compared the timing for three different approaches for a mass insert of 100k BLOB fields of 32 bytes each:
Generating a JSON array of hex strings and doing INSERT INTO the_table (blob_field) SELECT unhex(value) as blob_field from json_each(?), with various batch sizes
Using QueryBuilder to build a VALUES statement, with various batch sizes.
Inserting one by one using VALUES (?).
Here's the result:
Time for mass insert using JSON (batch size 100000): 204.063168ms
Time for mass insert using JSON (batch size 10000): 318.28208ms
Time for mass insert using JSON (batch size 1000): 785.099067ms
Time for mass insert using JSON (batch size 100): 3.351116507s
Time for mass insert using QueryBuilder (batch size 10000): 205.967325ms
Time for mass insert using QueryBuilder (batch size 1000): 734.117792ms
Time for mass insert using QueryBuilder (batch size 100): 3.353956729s
Time for mass insert one by one: 67.237277417s
QueryBuilder performs better, if you're within the limits of QueryBuilder. JSON isn't far behind, though, and doesn't have the same limits. (You're still limited by available memory, though.)
omg thank you i followed your instructions and extend the tauri sql wrapper.rs that uses sqlx.. to do that what u said.. i added insert_many..
on a generic sata ssd.
but yours seem more efficient than mine xD because u got 200ms. i got 300ms at 100k test..
.. last time it took tauri 46 seconds to manually insert 12k item with transaction and loop insert then commit xD
.. turso took 6 seconds to do it..
.. with your idea its now 300ms for 100k.
I really appreciate your post xD it helps me alot..
Edit: tried it on sqlite::memory: 1_000_000 items
Insertion of 1000000 items took: 2057ms (485947 items/sec)
Selection of 1000000 items took: 7880ms (126887 items/sec)
Activity
connec commentedon May 1, 2020
This seems a popular concern right now! I asked this question on Discord and the answer for now is this is not possible, unless you generate the query yourself (and lose a lot of the compile-time-safety features as a result).
There seems to be some activity in the area though:
COPYinto a temporary table thenINSERT ... FROM).greglearns commentedon May 1, 2020
@connec I missed those related topics! Thanks for pointing them out.
Yes, for me, this is the biggest need for interacting with SQL -- I can write SQL myself and make sure it is safe, and binding a few arguments isn't hard, but it's a pain to bind an arbitrary number of
($n, $n+1), ($n+2, $n+3), etc.!jsdw commentedon Jun 20, 2020
I ran into a similar issue. I think I have a solution (for now), but it is somewhat hideous:
The "trick" is that you can pass in a Vector of items to be a Postgres ARRAY type, and UNNEST that array to turn it into a set of rows. So, above, I basically split the thing I want to insert into a vec for each column of values (fortunately only 3 for me), which each get turned into a temporary table with row numbers. Once I have these, I can join them all on the row numbers to produce a final table of values, which I then pass to the INSERT.
It's pretty hideous, and I'd love to find a more concise or better approach, but it's the best I have so far!
I need to actually test it properly next, to make sure it does what I am hoping it does..
jsdw commentedon Jun 20, 2020
As an aside, I also tried doing a simpler approach of passing a single array of all of the values I wanted to update at once, but I hit a wall where SQLx did not understand the type of the array I was trying to provide, so that's what led me to splitting the array up and recombining it in SQL instead.
jsdw commentedon Jun 20, 2020
Just a quick FYI that, at least from a postgres POV, this works as I'd like. Here's a brief example:
shiftrtech commentedon Oct 24, 2020
Hi, is there a way to do this i need to make a 25 inserts at once
greglearns commentedon Oct 25, 2020
For Postgres, the below works, and is easy. Maybe this is good enough and nothing else is needed to support INSERTing multiple records, at least for Postgres.
shiftrtech commentedon Oct 25, 2020
@greglearns can i use this with
#[derive(sqlx::FromRow)]?greglearns commentedon Oct 25, 2020
@shiftrtech I haven't tried it, so I don't know. Let us know what you find out!
greglearns commentedon Oct 25, 2020
Slightly easier (IMHO cleaner) Sql:
itsfarseen commentedon Apr 30, 2021
Does handling this in the application have any disadvantages?
We could do this by doing multiple single inserts using a for loop right?
jplatte commentedon Apr 30, 2021
@itsfarseen Yes, doing it in a loop means a lot more back-and-forth between application and DB.
greglearns commentedon Apr 30, 2021
itsfarseen commentedon Apr 30, 2021
Is doing multiple single inserts that much inefficient?
For example consider a web app route POST /todos that let you insert 10 rows.
I understand that a post request will take longer to execute because now the request handler has to .await 10 times instead of just one time and other I/O operations can come in between those .awaits.
But the data the request handler has to send to postgres, isn't it almost same as above?
"Almost" because now there will be 10 headers, one for each row instead of 1 header for all 10 rows when we send data to postgres.
Comparing this with the overhead of doing the json conversion, wouldn't this be more efficient?
jplatte commentedon Apr 30, 2021
If the're on different servers that are "far apart" (in different datacenters) then the JSON solution is most likely faster, maybe substantially faster. If they're on the same machine then you're probably right and the JSON solution is slower, but not slow enough that you would notice outside of microbenchmarks. If it really matters, benchmark it for your specific situation.
14 remaining items
jprochazk commentedon Feb 11, 2022
I think streaming rows already captures any use cases I can think of for
Decode, can you elaborate a bit more?kevincox commentedon Apr 15, 2022
I had trouble inserting array fields here because
UNNESTon multi-dimensional arrays fully flattens the values (at least on postgres). I ended up switching from usingUNNESTto doing a huge cross join and usinggenerate_subscriptsto pick out the right entries.Here is the slightly simplified example.
I've only really tested with <50 rows but there is no obvious slowdown occurring here. It seems to be fairly fast.
That being said this is an incredibly bad API:
I would love to see a good interface here. Ideally I could just insert an
IntoIterator<Item: impl ToRow>or similar. Batching as needed could be handled automatically. It would be nice if this used the bulk-loading features of each DBMS but that may not be feasible because at least for postgresCOPYdoesn't allow returning anything.Iron-E commentedon Jun 3, 2022
Just noting that you can now use
QueryBuilder::push_valuesfor this purpose.jplatte commentedon Nov 11, 2022
@arturs706 please ask on StackOverflow, Discord (see README) or https://reddit.com/r/learnrust instead of hijacking random issues to ask unrelated questions.
pureliani commentedon Aug 14, 2023
@Iron-E's answer helped and i made it work with a query builder:
tgross35 commentedon Jan 26, 2024
In case anyone finds it useful, query builder can also be used with
ON DUPLICATE KEY UPDATEandRETURNINGclauses (only works with MariaDB, not MySQL).EXPECTED_RECORDSis an array of structs and the columnkeyis a unique key. I'm using this query to map a Rust enum to record IDs and ensure I only have one copy in the database (init step so there is no error handling).I think this is pretty clean, but maybe the checked macros could get some syntax to handle this too. Perhaps
joshtriplett commentedon May 25, 2024
For folks looking for a solution for sqlite (which doesn't have
UNNEST), I compared the timing for three different approaches for a mass insert of 100k BLOB fields of 32 bytes each:INSERT INTO the_table (blob_field) SELECT unhex(value) as blob_field from json_each(?), with various batch sizesQueryBuilderto build aVALUESstatement, with various batch sizes.VALUES (?).Here's the result:
QueryBuilderperforms better, if you're within the limits ofQueryBuilder.JSONisn't far behind, though, and doesn't have the same limits. (You're still limited by available memory, though.)Pascal-So commentedon Apr 24, 2025
@joshtriplett Thanks for taking the time to run this performance comparison! Do you happen to remember if that comparison was run inside a transaction or not? I'm guessing yes, since without transaction probably would have been much slower, right? No worries if you don't remember, you've already provided a lot of value either way
joshtriplett commentedon Apr 24, 2025
@Pascal-So I didn't try putting everything inside a single transaction; I just ran a separate
querycall for eachINSERT INTO.Here are some freshly collected numbers without a transaction:
And here are the numbers with a transaction:
Pascal-So commentedon Apr 24, 2025
@joshtriplett oh wow, that is pretty significant in some cases. Thank you for the quick and detailed response, much appreciated!
dns2utf8-novaziun commentedon May 9, 2025
The transaction looks like a relatively clean workaround for now
TomieAi commentedon Jul 24, 2025
omg thank you i followed your instructions and extend the tauri sql wrapper.rs that uses sqlx.. to do that what u said.. i added insert_many..
on a generic sata ssd.

but yours seem more efficient than mine xD because u got 200ms. i got 300ms at 100k test..
.. last time it took tauri 46 seconds to manually insert 12k item with transaction and loop insert then commit xD
.. turso took 6 seconds to do it..
.. with your idea its now 300ms for 100k.
I really appreciate your post xD it helps me alot..
Edit: tried it on
sqlite::memory:1_000_000 itemsI don't know if its good enough xD
HookedBehemoth commentedon Aug 1, 2025
In postgres, unnest with a SoA (e.g. soa_derive) works for me now.
Saves me from having to reshuffle my data before inserting.
woat commentedon Jan 27, 2026
friends, there MUST be a way to get bulk inserts to work with compile time macros
i think the query builder answer was a good shim, but its been 3 years already
i will contribute $100 usdc crypto to solve this friends