Skip to content

Instantly share code, notes, and snippets.

@mgarces
Last active August 29, 2015 13:58
Show Gist options
  • Save mgarces/9972412 to your computer and use it in GitHub Desktop.
Save mgarces/9972412 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text, sequence_name text) RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE 'SELECT setval( ''' || sequence_name || ''', ' || '(SELECT MAX(' || columnname || ') FROM ' || tablename ')';
exception when others then
raise notice 'Wrong column name, ignore';
END;
$body$ LANGUAGE 'plpgsql';
select reset_sequence(replace(S.relname, '_seq', ''), 'id', S.relname) from pg_class S where S.relkind = 'S';
select reset_sequence(replace(S.relname, '_seq', ''), 'sequence_id', S.relname) from pg_class S where S.relkind = 'S';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment