44

I would like to know how to insert data in postgresql using for loop?

I want to insert 1 to 1000 in row of id..

1
  • What is the actual problem you are trying to solve? Commented Dec 14, 2016 at 6:46

3 Answers 3

91

Please try below code to insert values in tables using for loop.

do $$
begin
for r in 1..1000 loop
insert into schema_name.table_name(id) values(r);
end loop;
end;
$$;
Sign up to request clarification or add additional context in comments.

1 Comment

God bless the fruit of your mother's womb
25

Use generate_series:

INSERT INTO tableName (id) SELECT * FROM generate_series(1, 1000);

4 Comments

is there a reason to avoid it? @Evan Carroll
@EvanCarroll In case you want to generate some test data, or want to performance benchmark, you can always use this.
Yes, it's good for test data. Reasons to avoid it -- if it's a real ID column, it should be an identity column. If it's numbers on output you should use ROW_NUMBER() OVER (), etc.
this one's faster than the loop
2
INSERT INTO sub_category (category_id, sub_category_id, price) 
SELECT 10001, gs, 5 FROM generate_series(1, 1000) AS gs;

Comments

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.