2

Suppose I have users stored as

select * from users_t where user_name like 'ABC%';

id   user_name  
1    ABC1
2    ABC2
..   ..

Now I need to loop through all user_name's and make that number of INSERTs into a different table, RECALLS_T. All the other columns are hard-coded constants that I define.

Assume the following table, with a Sequence called RECALLS_T_ID_SEQ on the ID:

id  created_by_user_name  field1   field2
1   ABC1                  Const1   Const2
2   ABC2                  Const1   Const2
..   ..                   ..       ..

How do I insert these in a Postgres loop?

ADDITIONAL QUESTION Also, what if I need to insert X (say 5) Recalls for each User entry? Suppose it's not a 1:1 mapping, but 5:1, where 5 is a hard-coded loop number.

1 Answer 1

3

You can use the select in the insert statement:

insert into recalls_t (created_by_user_name, field1, field2)
select user_name, 'Const1', 'Const2'
from users_t 
where user_name like 'ABC%';

Use the function generate_series() to insert more than one row for each entry from users_t. I have added the column step to illustrate this:

insert into recalls_t (created_by_user_name, field1, field2, step)
select user_name, 'Const1', 'Const2', step
from users_t 
cross join generate_series(1, 3) as step
where user_name like 'ABC%'
returning *

 id | created_by_user_name | field1 | field2 | step 
----+----------------------+--------+--------+------
  1 | ABC1                 | Const1 | Const2 |    1
  2 | ABC2                 | Const1 | Const2 |    1
  3 | ABC1                 | Const1 | Const2 |    2
  4 | ABC2                 | Const1 | Const2 |    2
  5 | ABC1                 | Const1 | Const2 |    3
  6 | ABC2                 | Const1 | Const2 |    3
(6 rows)

Live demo in Db<>fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks; also, what if I need to insert X (say 5) Recalls for each User entry? Suppose it's not a 1:1 mapping, but 5:1, where 5 is a hard-coded loop number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.