102
votes

I have a table that I am trying to update multiple values at once. Here is the table schema:

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

I have the user_id and want to insert multiple subservice_id's at once. Is there a syntax in Postgres that will let me do something like this

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

How would I do this?

5
If you want to insert them from a sequence, or using generate_series see dba.stackexchange.com/a/89544/16892 - rogerdpack

5 Answers

185
votes

Multi-value insert syntax is:

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

But krokodilko's answer is much slicker.

70
votes

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

30
votes

A shorter version of krokodilko's answer:

insert into user_subservices(user_id, subservice_id) 
values(1, unnest(array[1, 2, 3]));
13
votes

A slightly related answer because I keep finding 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]);
3
votes

More robust example, for when you need to insert multiple rows into some table for every 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;