Select multiple ids from a PostgreSQL sequence Select multiple ids from a PostgreSQL sequence postgresql postgresql

Select multiple ids from a PostgreSQL sequence


select nextval('mytable_seq') from generate_series(1,3);

generate_series is a function which returns many rows with sequential numbers, configured by it's arguments.

In above example, we don't care about the value in each row, we just use generate_series as row generator. And for each row we can call nextval. In this case it returns 3 numbers (nextvals).

You can wrap this into function, but I'm not sure if it's really sensible given how short the query is.


There is a great article about this exact problem: "getting multiple values from sequences".

If performance is not an issue, for instance when using the sequence values dwarfs the time used to get them or n is small, then the SELECT nextval('seq') FROM generate_series(1,n) approach is the simplest and most appropriate.

But when preparing data for bulk loads the last approach from the article of incrementing the sequence by n from within a lock is appropriate.


CREATE OR REPLACE FUNCTION foo() RETURNS SETOF INT AS $$DECLARE    seqval int; x int;BEGINx := 0;WHILE x < 100 LOOP    SELECT into seqval nextval('f_id_seq');    RETURN NEXT seqval;    x := x+1;END LOOP;RETURN;END;$$ LANGUAGE plpgsql STRICT;

Of course, if all you're trying to do is advance the sequence, there's setval().

You could also have the function take a parameter for how many times to loop:

CREATE OR REPLACE FUNCTION foo(loopcnt int) RETURNS SETOF INT AS $$DECLARE    seqval int;           x int;BEGINx := 0;WHILE x < loopcnt LOOP    SELECT into seqval nextval('f_id_seq');    RETURN NEXT seqval;x := x+1;END LOOP;RETURN;END;$$ LANGUAGE plpgsql STRICT;