6

In database migration script (psql) I want to create sequence starting from certain value queried from table, like:

CREATE SEQUENCE book_id_seq START ( SELECT MAX(id) + 1 FROM book.book );

or tried to set \set start (SELECT MAX(id) + 1 FROM book.book) to use variable like:

CREATE SEQUENCE book_id_seq START :'start';

But using \set did not inerpret the query.

Another way setting variable did not work also

start := SELECT MAX(id) + 1 FROM book.book;

gave error:

ERROR:  syntax error at or near ":="
LINE 1: start := SELECT MAX(id) + 1 FROM book.book;

Selecting value INTO does not help also, because accessing needs another SELECT query.

Using static value works fine:

\set start 33
CREATE SEQUENCE book_id_seq START :'start'::int;

How to use dynamic starting value?

Postgres 9.6

2
  • Why do you want to use a sequence? Just define a serial value. Commented May 18, 2018 at 12:18
  • @GordonLinoff it is relevant to my other Q/A stackoverflow.com/a/50388597/196241, need to handle separate sequences for one table, to summarize problem in short. Commented May 18, 2018 at 12:21

1 Answer 1

10

you can use setval() after you created the sequence:

CREATE SEQUENCE book_id_seq;
select setval('book_id_seq', (SELECT MAX(id) + 1 FROM book.book));
Sign up to request clarification or add additional context in comments.

1 Comment

Nice approach, still keen to understand, how to assign dynamic value in script.

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.