How to insert multiple values ​​into a postgres table at once?

I have a table in which I try to update several values ​​at once. Here is the table layout:

Column | Type | Modifiers ---------------+---------+----------- user_id | integer | subservice_id | integer | 

I have user_id and want to insert several subservice_id . Is there any syntax in Postgres that will allow me to do something like this

 insert into user_subservices(user_id, subservice_id) values(1, [1, 2, 3]); 

How should I do it?

+50
postgresql
Dec 28 '13 at 13:20
source share
5 answers

Try:

 INSERT INTO user_subservices(user_id, subservice_id) SELECT 1 id, x FROM unnest(ARRAY[1,2,3,4,5,6,7,8,22,33]) x 

Demo: http://www.sqlfiddle.com/#!15/9a006/1

+32
Dec 28 '13 at 13:31
source share

The syntax for adding multiple values ​​is:

 insert into table values (1,1), (1,2), (1,3), (2,1); 

But crocodile's answer is much more complex.

+106
Dec 29 '13 at 0:38
source share

A slightly related answer, because I constantly find this question every time I try to remember this solution. Insert multiple rows with multiple columns :

 insert into user_subservices (user_id, subservice_id) select * from unnest(array[1, 2], array[3, 4]); 
+6
Sep 28 '16 at 9:12
source share

The shorter version of krokodilko answers:

 insert into user_subservices(user_id, subservice_id) values(1, unnest(array[1, 2, 3])); 
+4
Mar 18 '17 at 14:16
source share

A more reliable example is when you need to insert multiple rows into some table for each row in another table:

 INSERT INTO user_subservices (user_id, subservice_id) SELECT users.id AS user_id, subservice_id FROM users CROSS JOIN unnest(ARRAY[1,2,3]) subservice_id; 

`` ``

0
Jul 19 '17 at 11:02
source share



All Articles