Skip to content

Instantly share code, notes, and snippets.

@chanmix51
Last active August 29, 2015 14:01
Show Gist options
  • Save chanmix51/f3d26be648c47af52fe8 to your computer and use it in GitHub Desktop.
Save chanmix51/f3d26be648c47af52fe8 to your computer and use it in GitHub Desktop.
Restart sequences after a migration
create or replace function restart_sequence(seq_name varchar) returns void language plpgsql as $func$
declare
maxint bigint;
table_name varchar;
begin
table_name := left(seq_name, -7);
execute 'select max(id) + 1 from '||table_name into maxint;
if maxint is not null then
execute 'alter sequence '||seq_name||' restart with '||cast(maxint as text);
end if;
end;
$func$
;
@chanmix51
Copy link
Author

select restart_sequence(cast(relname as text)) from pg_catalog.pg_statio_all_sequences where schemaname = 'public';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment