0

I have Table1 with rows I want to iterate over, and insert values from those rows of data into another table.

Table1Name     ->      ID      Name  Date        Type
--------               -------------------------------
a                      101     a     2021-07-01  original
b                      139     b     2021-07-04  original
c                      322     c     2021-07-08  original
d                      431     d     2021-07-09  original

So basically pseudo is:

Loop over Table1:
    INSERT INTO Table2 (id, name, date) VALUES (random(), Table1.name, NOW(), 'original')

Just looping through Table1, adding in one of its values every time.

2
  • Sample data and desired results would really help. Commented Jul 9, 2021 at 14:25
  • @GordonLinoff added some extra details Commented Jul 9, 2021 at 14:49

1 Answer 1

3

I think you just want an INSERT INTO ... SELECT here:

INSERT INTO Table2 (id, name, date)
SELECT RANDOM(), name, NOW()
FROM Table1;

Most SQL operations are inherently set based, meaning if you want to insert all records from one table into another, the operation would be viewed as a single thing.

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

4 Comments

hey I added some more details, there are other values I'd want to pass in too.
@chung I have updated my answer, but I'm sticking with my general premise.
oh I didn't know you could add like "RANDOM()" into a select, thanks!
Could/Should you use something like nextval() for an id column which is likely to be a serial datatype?

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.