Regal Paris
Regal Paris

Reputation: 339

How to insert with loops in postgresql

I am trying to insert a number of rows to a table where values came from a select query

insert into article_rel (x_id, y_id) VALUES (12, (SELECT id from table where name = 'string')

this should be the same as executing this

insert into article_rel (x_id, y_id) VALUES (12, 1)
insert into article_rel (x_id, y_id) VALUES (12, 3)
insert into article_rel (x_id, y_id) VALUES (12, 4)

and so on.

I saw this How to use a SQL for loop to insert rows into database? but I'm not sure how can this help me

Thanks in advance,

Upvotes: 3

Views: 3345

Answers (1)

Rimas
Rimas

Reputation: 6024

Use this query:

INSERT INTO article_rel (x_id, y_id)
  SELECT 12, id
  FROM table_name
  WHERE name = 'string'

Upvotes: 4

Related Questions