0

I would like to insert new row in profit table for each user that exist in db: select id * from users. The number of users is dynamic, so I need to fetch them all. I need some loop in postgres sql. I have problem to figure it out on my own. It would be something like that:

select id * from users as user_ids

for (each userId in user_ids) {
 insert into profit (user_id, value) values (userId, 23);
}

Can I ask You for help? I've went for many questions already:

Insert new row with data computed from other rows

postgresSQL insert multiple rows, of id returned from select queries

No luck so far

masterdany88
  • 5,041
  • 11
  • 58
  • 132

1 Answers1

2

Thinking in "loops" is almost always wrong when working with SQL. You need to think in terms of sets and how you operate on them. SQL statement describe exactly that: how to retrieve a set and what to do with that set of rows.

In this case, you can use a SELECT statement as the source for an INSERT:

insert into profit (user_id, value) 
select id, 23
from users;

Note that you don't have a values clause in this case.