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
{{ message }}
Repository navigation
How to insert multiple rows with a single query? #957
I have n number of items. I would like to add them all with a single insert query.
insert into testtable(id,name) values (1,"jack"),(2,"john"),(3,"jill");
I have an array for my rows, and I like to add them all in. So, if I provide pg the correct string (after manually forming it in a variable) it works perfectly fine, but this all seemed a bit pointless to me. I expect pg to handle arrays for me as well, but I'm unable to find the option for that. So I'm asking, is this possible?
How can I insert multiple rows from an array of rows, with a single insert query with this library?
Would love to know. Thank you.
Reacted by Stevie Huh, Jason Kim, Luke Schlangen, Aaron Asch, Thomas Pritchard, Tim Phillips, t4christ, Danylo Mysak, Raymond Pang, Nasruddin Ali and 12 more
var query = 'INSERT INTO table (SELECT (data->>'c1')::int, (data->>'c2')::text FROM (SELECT json_array_elements($1::json) AS data) tmp)'
var data = JSON.stringify([{c1: 1, c2: 'text1'},{c1: 2, c2: 'text2'}])
client.query(query, [data], ...)
Formatted version of the query:
INSERT INTO table (
SELECT
-- extract the props from the json object so that they match the table cols
(data->>'c1')::int, (data->>'c2')::text
FROM (
-- expand the json array
SELECT json_array_elements($1::json) AS data
) tmp
)
Reacted by Martin Charles, Amin Roosta, Larbi, CeliaDoolaegheAdeo and Jacob Doherty
pg.query("INSERT INTO testtable (id, name) SELECT * FROM UNNEST ($1::int[], $2::text[])",[[1,2,3],["Jack","John","Jill"],])
Reacted by Dexter Miguel, timurgarif, Arnaud Benhamdine, Andre Rabold, John Ryder, Luke McGregor, Teemu Kontio, Tim Qian, Luc Leray, Luke Schlangen and 62 more
Reacted by Peita Lin, Денис Сергеевич Басковский, Igor and ArturFormella
Reacted by Luc Leray, Luke Schlangen, Daniel Fredriksson, Pablo De Nadai, Luna-zhao, futpib, Peter Kupietz, Sal Rahman, Zach Schnell, Emil Laine and 15 more
Reacted by Daniel Fredriksson, Pablo De Nadai, Sal Rahman, Thomas Pritchard, Ally Weir, Branimir Klarić, M Fahru, acstacey, Pedro Carvalho, Douglas Wille and 10 more
Reacted by petersantoso94, Yurii Holskyi, Jan Jongboom, daditto, Mahesh C. Regmi, alikhanoitan, Andrei Gatej, MarcLlobet and ensconced
This is not an ORM, this library just executes queries.
You don't need an ORM for that. PostgreSQL supports this natively, as stated in their docs
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
Reacted by Matt Swensen, Kilian Ciuffolo, Matthew Streatfield, GitStorageOne, Kamil Tomšík, Ramiro, Brian Williams, Emil Laine, Code Scratcher, contractor-jim and 26 more
Reacted by t4christ, Peita Lin, Robin Nagpal, Hafiz Suara, Anton Dmytriichuk, Pablo Nuñez, Иван Вольнов, Nono - AC, Nuno Jesus, Dominik Suszczewicz and 12 more
Since Postgres supports multi-record inserts using syntax.
INSERT INTO videos (title, author) VALUES
('Peru is a nice country.', 'limaGuy'),
('Breaking bad is a great show.', 'mikeGuy'),
('I like the winter.', 'novemberGuy');
I wrote a helper function called expand. It creates the query placeholders.
varvideos=[["Peru is a nice country.","limaGuy"],["Breaking bad is a great show.","mikeGuy"],["I like the winter.","novemberGuy"]]Query(`INSERT INTO videos (title, author) VALUES ${expand(videos.length,2)}`,flatten(videos))
Reacted by ziauddin10p, Seun Somefun, isami🍣, Jaydeep Solanki, mark, AlexandreLoub, Morgan Galvin, Alfian Pramudita, Jonathan Cardoso, Rodrigo Sliachticas and 35 more
var query = 'INSERT INTO table (SELECT (data->>'c1')::int, (data->>'c2')::text FROM (SELECT json_array_elements($1::json) AS data) tmp)'
var data = JSON.stringify([{c1: 1, c2: 'text1'},{c1: 2, c2: 'text2'}])
client.query(query, [data], ...)
Formatted version of the query:
INSERT INTO table (
SELECT
-- extract the props from the json object so that they match the table cols
(data->>'c1')::int, (data->>'c2')::text
FROM (
-- expand the json array
SELECT json_array_elements($1::json) AS data
) tmp
)
is there any explanation why you use tmp as alias when it's not used anywhere?
INSERT INTO registered_groups
SELECT (data->>'periode')::text, (data->>'group_id')::int, (data->>'user_id')::intFROM (SELECT json_array_elements($1::json) AS data)
ON CONFLICT (periode, group_id, user_id) DO NOTHING
Activity
vitaly-t commentedon Mar 6, 2016
zettam commentedon Mar 7, 2016
vitaly-t commentedon Mar 7, 2016
langpavel commentedon Mar 10, 2016
Prepare your insert statement
rpedela commentedon Mar 22, 2016
Using pg-format with a nested array:
Disclaimer: I wrote pg-format.
awenger commentedon Jun 17, 2016
You could also do something like:
Formatted version of the query:
joskuijpers commentedon Jun 21, 2016
mrxgodfather commentedon Apr 20, 2017
charmander commentedon Apr 20, 2017
@x0days That’s for MySQL, not PostgreSQL.
@zettam:
barbu110 commentedon Apr 21, 2018
You don't need an ORM for that. PostgreSQL supports this natively, as stated in their docs
bloodorca commentedon Oct 4, 2018
Since Postgres supports multi-record inserts using syntax.
I wrote a helper function called expand. It creates the query placeholders.
ZiaDev commentedon May 9, 2019
nhevia commentedon Nov 12, 2020
This is great.
Since ES6 you can simplify using Array.prototype.flat() instead of the
flattenfunctionmymirai-nikki commentedon Nov 27, 2025
is there any explanation why you use
tmpas alias when it's not used anywhere?charmander commentedon Nov 27, 2025
@mymirai-nikki
mymirai-nikki commentedon Nov 29, 2025
I tried without
tmp:and no error occurred?
charmander commentedon Nov 29, 2025
@mymirai-nikki Ah, that requirement was dropped in PostgreSQL 16.