11

I need to get following SQL script syntax right. In postgres, you can't really chain "alter sequence" with "select max(id)". So what's the right way to write script in a way that PostgreSQL accepts it?

Here is the script so you can have an idea what I need:

 alter SEQUENCE notification_settings_seq START with (select max(id) from game_user)
1
  • 2
    Just run this command: SELECT setval('my_table_seq', (SELECT max(id) FROM my_table)); Commented Oct 1, 2019 at 13:04

1 Answer 1

19

This restarts your sequence with new value:

do $$
declare maxid int;
begin
    select max(id) from game_user into maxid;
    execute 'alter SEQUENCE seq_name RESTART with '|| maxid;   
end;
$$ language plpgsql
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the fast reply. I edited a bit but it does what I need. Apparently, this question has already been answered. My bad for posting duplicates. დიდი მადლობა!
@Amiko - You're welcome. გაიხარე ))
SELECT setval('my_table_seq', (SELECT max(id) FROM my_table));
If sequence contains uppercase letters in name: SELECT setval(' "Foo" ', 42); Notice the double quotes inside the single quotes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.