9

Background Information:

I need to auto generate a bunch of records in a table. The only piece of information I have is a start range and an end range. Let's say my table looks like this:

     id 
     widgetnumber

The logic needs to be contained within a .sql file.
I'm running postgresql

Code

This is what I have so far... as a test... and it seems to be working:

DO $$
DECLARE widgetnum text;
BEGIN
    SELECT 5 INTO widgetnum;

    INSERT INTO widgets VALUES(DEFAULT, widgetnum);
END $$;

And then to run it, I do this from a command line on my database server:

testbox:/tmp# psql -U myuser -d widgets -f addwidgets.sql 
DO

Questions

  1. How would I modify this code to loop through a range of widget numbers and insert them all? for example, I would be provided with a start range and an end range (100 to 150 let's say)

  2. Can you point me to a good online resource to learn the syntax i should be using?

Thanks.

1
  • Why the DO block? Your example can be simplified to a single insert into widgets (widgetnumber) values (5); Commented Dec 23, 2016 at 16:28

2 Answers 2

20

How would I modify this code to loop through a range of widget numbers and insert them all?

You can use generate_series() for that.

insert into widgets (widgetnumber)
select i
from generate_series(100, 150) as t(i);

Can you point me to a good online resource to learn the syntax i should be using?

https://www.postgresql.org/docs/current/static/index.html

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

5 Comments

how do i handle the "DEFAULT" value that autogenerates the pk?
and do i still need to declare the variable widgetnumber?
If you omit the id column from your insert (as the suggested generate series command does) then any DEFAULT values will be automatically handled by the database.
you don't need plpgsql at all, just use the generate_series command in straight sql.
xzilla, i see. but i still want to know the answer about how to insert another value before the "i" variable ... because I have to populate a few other tables in similar way. But I guess it's best to just ask another question. Thanks for the help
1
dvdrental=# \d test
                       Table "public.test"
 Column |          Type          | Collation | Nullable | Default
--------+------------------------+-----------+----------+---------
 id     | integer                |           |          |
 name   | character varying(250) |           |          |

dvdrental=# begin;
BEGIN
dvdrental=# insert into test(id,name) select generate_series(1,100000),'Kishore';
INSERT 0 100000

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.