Skip to content

Instantly share code, notes, and snippets.

@geo-stanciu
Last active November 16, 2019 19:44
Show Gist options
  • Save geo-stanciu/70deb879b2c90c56b3baf47d5a524bf6 to your computer and use it in GitHub Desktop.
Save geo-stanciu/70deb879b2c90c56b3baf47d5a524bf6 to your computer and use it in GitHub Desktop.
Reset sequence values in PostgreSQL
do $$
declare
r record;
lMaxId bigint;
dbName text := 'devel';
begin
for r in with seq as (
select
table_name,
column_name,
substring(substring(column_default from position(chr(39) in column_default) + 1) from 1 for position(chr(39) in substring(column_default from position(chr(39) in column_default) + 1)) - 1 ) as sequence_name
from
information_schema.columns
where
table_catalog = dbName
and column_default like 'nextval%')
select
table_name,
column_name,
sequence_name,
'SELECT MAX(' || quote_ident(column_name) || ') FROM ' || quote_ident(table_name) AS max_id
from
seq
LOOP
EXECUTE r.max_id INTO lMaxId;
RAISE NOTICE 'trying to set % to %', r.sequence_name, lMaxId;
EXECUTE FORMAT('SELECT setval(%L, %s)', r.sequence_name, lMaxId);
END LOOP;
end $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment